python-函数-高阶函数

版权声明:所有代码均为自己总结,若有雷同请勿模仿 https://blog.csdn.net/weixin_44253023/article/details/90199832
filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。
例如判断奇偶数
def is_odd(x):
    return x % 2 == 1
filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
输出结果:
[1, 7, 9, 17]
filter在python3.x中生成是迭代器
filter在python2.x中生成是列表

map函数的用法:
在python3.x中会返回一个迭代器
在python2.x中会返回一个列表

在python2.x中
def f(x):
    return x*x
print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])

输出结果:
[1, 4, 9, 10, 25, 36, 49, 64, 81]

在python3.x中
def f(x):
    return x*x;
a=map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]);
l=[];
for i in a:
	l.append(i)l;
print(l);
输出结果:
[1, 4, 9, 10, 25, 36, 49, 64, 81]

def f(x,y):
	return x+y;
reduce(f, [1, 3, 5, 7, 9]);
输出结果:
25
还可以传入第三个参数,作为计算的初值。
reduce(f, [1, 3, 5, 7, 9], 100)
输出结果:
125
python3.x中已经移除reduce()函数,需要从functools模块中进行调用

reduce()函数也是Python内置的一个高阶函数。reduce()函数接收的参数和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值

猜你喜欢

转载自blog.csdn.net/weixin_44253023/article/details/90199832