python内置常用内置方法详解

# print(locals())
# print(globals())

 def func():
     x = 1
     y = 1
    print(locals())  # 函数内部的变量
     print(globals())  # 当前程序的变量


 func()
# 2.eval,exec,和compile
 res = eval("1+2+1")
 print(res)  # eval  有返回值  只能运行字符串
 res = exec("1+1+10")  # 可以执行字符串 亦可以执行函数的字符串  没有返回值
print(res)
# compile  # 做编译
com = compile('1+2+3', '', mode='eval')  # 节省时间  先编译 这样在执行会速度加快
 print(eval(com))
 print(eval('1+2+3'))  # 这句效果和上面的compile()效果一样

 print("AAA", sep=",")  # print(value, ..., sep=' ', end='
', file=sys.stdout, flush=False)
#  end最后的结束  默认问换行  file 可以写入文件中,
# 前提是必须打开文件
# 小练习
 import sys, time
 for i in range(0, 101, 2):
     time.sleep(0.1)
     char_num = i // 2
     per_str = '
%s%% : %s' % (i, '*' * char_num)
     print(per_str, file=sys.stdout, flush=True)
# input()  type()
# open  函数  mode= r w a (r+ w+ a+   读写,写读,追加)
# f.seek(5)把光标移动到指定位置
# callable:查看能不能调用
 print(callable(123))  # 数字字符不可调用
 print(callable(open))  # open 可调用函数
# dir  查看数据类型所拥有的方法
# 取商/余
 res = divmod(7, 3)
 print(res)  # 除法 打印 返回除商跟余数组成的元祖
# 计算最小值
 print(min(1,2,3,4))
 print(min([5,6]))
# 计算最大值
 print(max(1,2,3,4))
 print(max([5,6]))
# 计算和必须不是散列 列表元祖可以计算
 res=sum([12,34,5,])  #返回和值
 res=sum(1,2,)  #报错  不支持散列
 round pow  精度 与 幂运算
# 数据结构相关
 l = [1, 2, 3, 4]
 res=l.reverse()  #直接把列表字段倒叙修改了原来的列表 没有返回值
 res = list(reversed(l))  # 把列表翻转 返回一个可被list的数据对象
 print(l)

 print(res)
 bytes
 s='你好'
 sb=bytes(s,encoding='utf-8')  #把utf8的字符类型装换成bytes类型 需要制定以前的编码
 print(sb)
 print(sb.decode('utf-8'))
#  enumerate  列表转换成索引加值的元祖   字典是索引.key 值转换成元祖
 l=[1,23,44]
 dict={1:2,3:4}
 for i  in enumerate(dict):
     print(i)
# all和any
 print(all([1, 23, 4, 0]))   #有一个是0  就False  判断列表有一个为空 就是false了
 print(any([0, 2, 3]))  #
#map():我要对我的列表当中的每一个值去做函数里面的操作
 res = map(lambda x: x + 1, [1, 2, 3, 4])  # 返回的是一个对象的形式
 print(list(res))
#filter():  从一个列表当中找到所有符合筛选条件的,在组成一个新列表

 res = filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6])
 print(list(res))

  

原文地址:https://www.cnblogs.com/zjcode/p/8549700.html