例一

⼤多数时候,我们要把列表中所有元素⼀个个地传递给⼀个函数,并收集输出。⽐⽅说:
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
    squared.append(i**2)

Map可以让我们⽤⼀种简单⽽漂亮得多的⽅式来实现。就是这样: 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 = list(map(lambda x: x(i), funcs))
  print(value)

输出:

[0, 0]
[1, 2]
[4, 4]
[9, 6]
[16, 8]

 

相关文章:

  • 2022-12-23
  • 2021-06-17
  • 2021-10-11
  • 2021-08-19
猜你喜欢
  • 2021-07-24
  • 2021-09-24
  • 2021-12-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案