python3 中的 map,reduce,filter函数

在python2 中直接打印map,filter函数会直接输出结果。但在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))))

运行结果如下

['ADAM', 'LISA', 'BART']
125
[1, 7, 9, 17]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

猜你喜欢

转载自blog.csdn.net/frone/article/details/45561029