Python中map(),filter(),reduce()及sum()的使用方法比较

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/merryxuan/article/details/89332757

看《python学习手册》看到列表那一节,发现有提到map函数和filter函数,作者并没有作细讲。自己总结了下。

以下例子都以列表作为示例

1.map函数

map函数有两种使用方法:

(1) 可以做判断,判断列表里的元素是否符合lambda给的函数映射。返回值为True和False。例如:

L1 = list(map(lambda x:x%2 ==0,range(1,15)))
print('L1 is : {} '.format(L1))
#L1 is : [False, True, False, True, False, True, False, True, False, True, False, True, False, True] 

(2) 按lambda函数式计算,返回计算后的结果,例如:

L3 = list(map(lambda x:x*x,range(1,15)))
print('L3 is : {}'.format(L3))
#L3 is : [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196]

2.filter函数

filter函数用法和其名称相符,过滤出符合lambda函数式的元素,可以和L1的map做比较,例如:
L2 = list(filter(lambda x:x%2 ==0,range(1,15)))
print('L2 is : {}'.format(L2))
#L2 is : [2, 4, 6, 8, 10, 12, 14]

3.reduce函数

reduce函数是将列表中的元素从左到右将列表中的元素按lambda函数式计算一次,返回一个最终结果。例如:

L4 = reduce(lambda x,y: x+y,[1,2,3,4])
print('L4 is : {}'.format(L4))
#L4 is : 10

计算的顺序为(((1+2)+3)+4)=10

4.sum函数

sum函数没别的,就是列表内元素累加,返回最终结果。由于python列表求和比较常用,所以专门有了这个函数。例:

L5 = sum(range(1,20))
print('L5 is : {}'.format(L5))
#L5 is : 190

猜你喜欢

转载自blog.csdn.net/merryxuan/article/details/89332757