问题描述
以下python教程说:
但是,这里没有提到一个例子,它是列表推导如何代替reduce()
的例子,我也没有想到一个例子.
能否有人解释如何通过列表理解来实现类似约简的功能或确认不可能?
理想情况下,列表理解是创建一个新列表.引用官方文档,
而reduce
用于将可迭代项减少为单个值.引用 functools.reduce
,
因此,列表理解不能用作reduce
的直接替代.
The following python tutorial says that:
However, it does not mention an example how a list comprehension can substitute a reduce()
and I can't think of an example how it should be possible.
Can please someone explain how to achieve a reduce-like functionality with list comprehension or confirm that it isn't possible?
Ideally, list comprehension is to create a new list. Quoting official documentation,
whereas reduce
is used to reduce an iterable to a single value. Quoting functools.reduce
,
So, list comprehension cannot be used as a drop-in replacement for reduce
.
这篇关于列表理解可替代Python中的reduce()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!