本文共 873 字,大约阅读时间需要 2 分钟。
格式:map(func, *iterables)
map()函数是将func作用于iterables中的每一个元素,并用一个列表给出返回值。如果func为None,作用同zip()。
传入一个可迭对象
def func(x): return x*xlists = [1, 2, 3, 4]l = list(map(func, lists))print(l)结果:[1, 4, 9, 16]
传入两个可迭对象
def func(x, y): return x+ylists = [1, 2, 3, 4]lists2 = [1, 2, 3, 4]l = list(map(func, lists, lists2))print(l)结果:[2, 4, 6, 8]
格式:reduce(function, sequence, initial=None)
reduce函数即为化简,它是这样一个过程:每次迭代,将上一次的迭代结果(第一次时为init的元素,如没有init则为seq的第一个元素)与下一个元素一同执行一个二元的func函数。在reduce函数中,init是可选的,如果使用,则作为第一次迭代的第一个元素使用。
例子:
不传入默认值from functools import reducelists = ['a', 'b', 'c', 'd']r = reduce(lambda x, y: x+y, lists)print(r)结果:abcd
传入默认值
from functools import reducelists = ['a', 'b', 'c', 'd']r = reduce(lambda x, y: x+y, lists, '你好')print(r)结果:你好abcd
转载地址:http://axfll.baihongyu.com/