Map
map(function_to_apply, list_of_inputs)items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = map(lambda x: x(i), funcs)
print(list(value))
# 译者注:上面print时,加了list转换,是为了python2/3的兼容性
# 在python2中map直接返回列表,但在python3中返回迭代器
# 因此为了兼容python3, 需要list转换一下
# Output:
# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]最后更新于
这有帮助吗?