gpt4 book ai didi

python : can reduce be translated into list comprehensions like map, lambda 和过滤器?

转载 作者:IT老高 更新时间:2023-10-28 20:22:14 29 4
gpt4 key购买 nike

在使用 python 编程时,我现在通过使用列表推导来避免使用 maplambdafilter,因为它更易于阅读并且在执行。但是reduce也可以替换吗?

例如一个对象有一个操作符 union(),它作用于另一个对象 a1.union(a2),并给出第三个相同类型的对象。

我有一个对象列表:

L = [a1, a2, a3, ...]

如何将所有这些对象的 union() 与列表推导式结合起来,相当于:

result = reduce(lambda a, b :a.union(b), L[1:], L[0])

最佳答案

reduce 是 not among the favored functions 已经不是什么 secret 了的 Pythonistas。

一般来说,reduceleft fold on a list

在 Python 中编写折叠在可迭代对象上向左或向右折叠在概念上很容易:

def fold(func, iterable, initial=None, reverse=False):
x=initial
if reverse:
iterable=reversed(iterable)
for e in iterable:
x=func(x,e) if x is not None else e
return x

如果没有一些残暴的 hack,这将无法在推导中复制,因为推导中没有累加器类型的函数。

只需使用 reduce —— 或者写一个对你更有意义的。

关于python : can reduce be translated into list comprehensions like map, lambda 和过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24410420/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com