当前位置: 代码迷 >> 综合 >> 关于map,reduce,filter函数的使用学习
  详细解决方案

关于map,reduce,filter函数的使用学习

热度:72   发布时间:2023-12-14 14:18:33.0
import functools
list2 = [1, 2, 3, 4, 5]
list3 = [1, 2, 3, 4, 5]
list4 = [1, 2, 3, 4, 5]
# map 用来对数列中每个对象执行函数
def map_test(a):return a * 3
# reduce 对序列中的对象做操作并把返回值作为下一次操作的第一个参数,序列中下一个对象为第二个参数
def reduce_test(a, b):return a * b
# filter 用于过滤序列,并返回符合条件的元素
def filter_test(a):return a % 2 == 0
test1 = map(map_test, list2)
test2 = functools.reduce(reduce_test, list3)
test3 = filter(filter_test, list4)
# 想要把map 和 filter返回元素作为列表,则用List转换序列类型。而reduce则直接返回值
print(list(test1))
print(test2)
print(list(test3))

返回值:

[3, 6, 9, 12, 15]
120
[2, 4]

  相关解决方案