常见内置函数
查看内置函数:print(dir(__builtins__))
常见内置函数:
①len() 求长度
>>> len({'a':1,'b':2,'c':3})
3
>>> len({1,2,3})
3
>>> len([1,2,3])
3
>>> len('123')
3
②min() 求最小值
>>> min([2,6,1,5])
1
③max() 求最大值
>>> max([2,6,1,5])
6
④sum() 求和
>>> sum([2,6,1,5])
14
⑤sorted() 排序
>>> sorted([2,6,1,5])
[1, 2, 5, 6]
⑥reversed() 反向
>>> print(list(reversed([2,6,1,5])))
[5, 1, 6, 2]
>>> print(tuple(reversed([2,6,1,5])))
(5, 1, 6, 2)
⑦enumerate() 返回一个可以枚举的对象,返回(index,value)
>>> list(enumerate('asdfgwe'))
[(0, 'a'), (1, 's'), (2, 'd'), (3, 'f'), (4, 'g'), (5, 'w'), (6, 'e')]
>>> list(enumerate(['a','g','h','d','b','f']))
[(0, 'a'), (1, 'g'), (2, 'h'), (3, 'd'), (4, 'b'), (5, 'f')]
也可以指定索引起始位置
>>> list(enumerate(['a','g','h','d','b','f'],3))
[(3, 'a'), (4, 'g'), (5, 'h'), (6, 'd'), (7, 'b'), (8, 'f')]
无序对象也有伪索引
>>> list(enumerate({'a','g','h','d','b','f'}))
[(0, 'a'), (1, 'g'), (2, 'f'), (3, 'h'), (4, 'd'), (5, 'b')]
字典只取key
>>> list(enumerate({'a':11,'g':22,'h':33,'d':44,'b':55,'f':66}))
[(0, 'a'), (1, 'g'), (2, 'h'), (3, 'd'), (4, 'b'), (5, 'f')]
⑧filter() 过滤器,返回符合要求的元素
>>> a=[1,2,3,4,5,6,7,8,9]
>>> list(filter(lambda x:x>4,a))
[5, 6, 7, 8, 9]
>>> a=['1','2','3','a','b','c']
>>> def zishu(x):
if x.isdigit():
return x
>>> list(filter(zishu,a))
['1', '2', '3']
⑨map() 加工对参数中每个元素应用于函数,返回一个map对象
>>> list(map(lambda x:x+1,[1,2,3,4,5,6]))
[2, 3, 4, 5, 6, 7]
用于两个列表相加时
>>> list(map(lambda x,y:x+y,[1,2,3,4,5,6],[2,4,6,8,10]))
[3, 6, 9, 12, 15]
⑩zip() 放入可迭代对象,将对象注意配对,符合木桶效应
>>> a=[6,8,2,4,5]
>>> b=('a','b','c','d')
>>> list(zip(a,b))
[(6, 'a'), (8, 'b'), (2, 'c'), (4, 'd')]
>>> a='132465'
>>> b=('a','b','c','d')
>>> list(zip(a,b))
[('1', 'a'), ('3', 'b'), ('2', 'c'), ('4', 'd')]
字典只取key
>>> b={'a':66,'b':55,'c':22,'d':33}
>>> a='132465'
>>> list(zip(a,b))
[('1', 'a'), ('3', 'b'), ('2', 'c'), ('4', 'd')]

浙公网安备 33010602011771号