Python 三大函数(Map、Filter、Reduce)

本文详细介绍了Python中的三种高阶函数:map、filter和reduce的使用方法及应用场景。通过具体的代码示例展示了如何利用这些函数简化编程任务,提高代码效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Map

将一个函数映射到一个输入列表的所有元素上。

items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))

# output:
[1, 4, 9, 16, 25]
map作用于一列表的函数:
def multiply(x):
    return (x*x)
def add(x):
    return (x+x)

funcs = [multiply, add]

for i in xrange(5):
    value = map(lambda x: x(i), funcs)
    print(list(value))

# Output:
# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]

注:上面print加list转换,是为了python2/3的兼容,在python2中map直接返回列表,但在python3中返回迭代器。

Filter:

过滤列表元素,返回符合要求的元素所组成的列表;
filter类似for循环,但更快。

number_list = range(-5, 5)
less_than_zero = filter(lambda x: x < 0, number_list)
print(list(less_than_zero))  

# Output: 
[-5, -4, -3, -2, -1]

Reduce:

对列表进行计算并返回结果。

# 计算列表乘积:
from functools import reduce
product = reduce( (lambda x, y: x * y), [1, 2, 3, 4] )

# Output: 
24

# 计算静默期:
count_times:func,计算静默时间
blank_ret:list
reduce(count_times, sorted(blank_ret))

作者:Chihwei_hsu
来源:http://chihweihsu.com
Github:https://github.com/HsuChihwei


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值