python中map的用法

好记性不如乱笔头,记下来总是好的。。。
回复
BG6RSH
帖子: 138
注册时间: 周日 6月 23, 2019 12:00 pm

python中map的用法

帖子 BG6RSH »

Map
Map会将一个函数映射到一个输入列表的所有元素上。这是它的规范:

规范
map(function_to_apply, list_of_inputs)
大多数时候,我们要把列表中所有元素一个个地传递给一个函数,并收集输出。比方说:
  1. items = [1, 2, 3, 4, 5]
  2. squared = []
  3. for i in items:
  4.     squared.append(i**2)
Map可以让我们用一种简单而漂亮得多的方式来实现。就是这样:
  1. items = [1, 2, 3, 4, 5]
  2. squared = list(map(lambda x: x**2, items))
大多数时候,我们使用匿名函数(lambdas)来配合map, 所以我在上面也是这么做的。 不仅用于一列表的输入, 我们甚至可以用于一列表的函数!
  1. def multiply(x):
  2.         return (x*x)
  3. def add(x):
  4.         return (x+x)
  5.  
  6. funcs = [multiply, add]
  7. for i in range(5):
  8.     value = map(lambda x: x(i), funcs)
  9.     print(list(value))
  10.     # 译者注:上面print时,加了list转换,是为了python2/3的兼容性
  11.     #        在python2中map直接返回列表,但在python3中返回迭代器
  12.     #        因此为了兼容python3, 需要list转换一下
  13.  
  14. # Output:
  15. # [0, 0]
  16. # [1, 2]
  17. # [4, 4]
  18. # [9, 6]
  19. # [16, 8]
回复