python的map,filter,reduce学习

python2,python3中map,filter,reduce区别:
1,在python2 中,map,filter,reduce函数是直接输出结果。

2,在python3中做了些修改,输出前需要使用list()进行显示转换,而reduce函数则被放到了functools包中

from functools import reduce
import math
def format_name(s):
    return s.upper()

def is_odd(x):
    return x % 2 == 1

def sqr_integer(x):
    r = math.floor(math.sqrt(x))
    return x == r*r

def f(x, y):
    return x + y
# map 把函数 f 依次作用在 list 的每个元素上,得到一个 iterator  并返回。
print(list(map(format_name, ['adam', 'LISA', 'barT'])))

# reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。reduce()还可以接收第3个可选参数,作为计算的初始值。
print(reduce(f, [1, 3, 5, 7, 9], 100))
# filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的iterator。
print(list(filter(is_odd, [1, 4, 6, 7, 9, 12, 17])))
print(list(filter(sqr_integer,range(100))))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

运行结果如下

['ADAM', 'LISA', 'BART']
125
[1, 7, 9, 17]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  • 1
  • 2
  • 3
  • 4
 
原文地址:https://www.cnblogs.com/sunshine-1/p/7441533.html