python常用内置函数的作用

abs()    #获取绝对值

chr()    #返回数字对应的ASCII字符

cmp(x,y)    #如果x<y 返回-1,x==y返回0 ,x> y返回1

compile()     #函数将一个字符串编译为字节代码。
str = 'for i in  [1,2,3,4,5,6,7] :print(i)'   #name
c = compile(str,'','exec')
exec(str)

exec()    #函数将一句string类型的python代码执行
str = 'for i in  [1,2,3,4,5,6,7] :print(i)'   #name
c = compile(str,'','exec')
exec(str)

eval()    #函数将一个算数表达式执行

dict()    #函数用来创建字典类型

zip()    #函数可以将多个可迭代的对象按照相同的index转化为最短的tuple
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)          # 与 zip 相反,可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]

dir()    #获取当前类型的方法
print(dir(list))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

divmod()    #函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。
print(divmod(7,2))   
(3, 1)

enumerate()    #把可遍历的对象组合成一个枚举对象,(索引,字段本身)
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # 小标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

execfile()    #函数可以用来执行一个文件。

format()    #用{}和:代替以前的%

from functools import reduce
a = 1
b = 2
print(a+1 if a>b else b+1) #列表推导式 3
lis = [1,2,3,4,5]
print([i for i in lis if i%2 ==0]) #列表推导式 [2, 4]
a = list(map(lambda x :x**2 if x%3 == 0 else x,lis)) # map
print(a) #[1, 2, 9, 4, 5]
b = reduce(lambda x,y:x+y,lis) #reduce 15
print(b)
print(list(filter(lambda x:x%3 ==0,lis))) #filter [3]
print(sorted(lis,reverse=True)) #sorted [5, 4, 3, 2, 1]
 

 

 

posted on 2018-01-19 19:30  特立独行的十楼  阅读(1551)  评论(0编辑  收藏  举报

导航