您的位置:首页 > 编程语言 > Python开发

Python 函数lambda(), filter(), map(), reduce()

2017-03-21 12:43 1216 查看
1 filter

filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)

比如

def f(x): return x % 2 != 0 and x % 3 != 0
x = filter(f, range(2, 25))

也可以用推导式这样写

x = [x for x in range(2, 25) if x % 2 != 0 and x % 3 != 0 ]
print ( x )

也可以用filter + lambda 这样写

x = filter( lambda x:x % 2 != 0 and x % 3 != 0, range(2, 25))
print ( x )

2 map

map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回,比如

data = map(lambda x: x*x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(data)

输出 [1, 4, 9, 16, 25, 36, 49, 64, 81]

再比如把列表的数字全部转为字符串

data = map(lambda x: str(x), [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(data)

3 reduce

reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算

比方说对一个序列求和,就可以用reduce实现

>>> def add(x, y):
...     return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: