- map(func, *iterables)
map接受两个参数,第一个是函数,第二个是可迭代对象。
test = [1,2,3,4.5]
list(map(lambda x:x*2, test)) # 此处自己定义函数也可以,不一定是匿名函数
返回:
[1, 4, 9, 20.25]
- filter(function or None, iterable)
filter可以筛选数据,第一个function是筛选条件,第二个是可迭代对象。
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # 筛选奇数
返回:
[1, 5, 9, 15]
- reduce(function, sequence[, initial])
reduce()可以将第二个参数sequence中的数据一个一个的进行function的操作。比如先处理第一个和第二个数值,然后再处理这两个的结果和第三个数,直到最后。
reduce()函数在python3版本中的全局命名空间已经被移除了,可以导入functools来使用。
from functools import reduce
reduce(lambda x, y : (x+1)*y, [1,2,3,5])
返回:80.
即((((1+1) * 2 ) + 1 ) * 3 + 1) * 5 = 80.
- zip(iter1 [,iter2 [...]])
zip()可以将可迭代对象打包成对应的元组形式,如下:
L1 = ['one', 'two']
L2 = [1, 2]
list(zip(L1, L2))
dict(zip(L1, L2))
可返回:[('one', 1), ('two', 2)]和{'one': 1, 'two': 2}
当两个列表不等长时:
L1 = ['one', 'two', 'other']
L2 = [1, 2, 3]
list(zip(L1, L2))
dict(zip(L1, L2))
返回: [('one', 1), ('two', 2)]和{'one': 1, 'two': 2}
与短的长度一致。
网友评论