map、filter、reduce函数

map

#函数需要⼀个参数
m1 = map(lambda x:x*x,[1,2,3])
print(list(m1)) #函数需要两个参数
m2 = map(lambda x,y:x+y,[1,2,3],[4,5,6])
print(list(m2)) def f1(x,y):
return (x,y)
l1 = [0,1,2,3,4,5,6]
l2 = ['Sun','M','T','W','T','F','S']
l3 = map(f1,l1,l2)
print(list(l3))

  输出

[1, 4, 9]
[5, 7, 9]
[(0, 'Sun'), (1, 'M'), (2, 'T'), (3, 'W'), (4, 'T'), (5, 'F'), (6, 'S')]

  

filter

from collections import Iterator
f1 = filter(lambda x:x%2, [1,2,3])
print(f1)
print(list(f1))
print(isinstance(f1, Iterator))

  输出

<filter object at 0x00000176DB8075C0>
[1, 3]
True

  

reduce

from functools import reduce
r1 = reduce(lambda x,y:x+y,[1,2,3,4])
r2 = reduce(lambda x,y:x+y,[1,2,3,4],5)
r3 = reduce(lambda x,y:x+y,['aa','bb','cc'],'dd')
print(r1)
print(r2)
print(r3)

  输出

10
15
ddaabbcc

  

上一篇:filter、map、sorted和reduce函数


下一篇:[刘阳Java]_快速搭建MyBatis环境_第2讲