python map函数

 例一

⼤多数时候,我们要把列表中所有元素⼀个个地传递给⼀个函数,并收集输出。⽐⽅说:
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]

 

posted @ 2018-11-11 12:23  anobscureretreat  阅读(156)  评论(0编辑  收藏  举报