如何使用Python的reduce()函数

Python提供了三个有用的全局函数,我们可以使用它们来处理集合:map()、filter()和reduce()。 提示:有时候,列表推导式更加合适,而且通常被认为更加“Pythonic”。 reduce()函数用于根据序列(如列表)计算一个值。 例如,假设你有一个存储为元组的费用列表,你想计算每个元组中某个属性的总和,比如每项费用的金额: expenses = [ ('Dinner', 80), ('Car repair', 120) ] 你可以使用循环来遍历它们: total = 0 for expense in expenses: total += expense[1] print(total) # 200 或者,你可以使用reduce()函数将列表减少为一个单一的值: from functools import reduce print(reduce(lambda a, b: a[1] + b[1], expenses)) # 200 reduce()函数不像map()和filter()一样默认可用。你需要从标准库模块functools中导入它。