列表理解可替代Python中的reduce() [英] List comprehension as substitute for reduce() in Python
问题描述
以下python教程说:
列表理解是lambda函数以及函数
map()
,filter()
和reduce()
的完全替代.
但是,这里没有提到一个例子,它是列表推导如何代替reduce()
的例子,我也没有想到一个例子.
能否有人解释如何通过列表理解来实现类似约简的功能或确认不可能?
理想情况下,列表理解是创建一个新列表.引用官方文档,
列表理解为创建列表提供了一种简洁的方法.常见的应用是创建新列表,其中每个元素是应用于另一个序列的每个成员的某些操作的结果或可迭代,或创建一个新的列表.满足一定条件的元素的子序列.
而reduce
用于将可迭代项减少为单个值.引用 functools.reduce
,
将两个自变量的函数从左到右累计应用于序列项,以便将序列简化为单个值.
因此,列表理解不能用作reduce
的直接替代.
The following python tutorial says that:
List comprehension is a complete substitute for the lambda function as well as the functions
map()
,filter()
andreduce()
.
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,
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
whereas reduce
is used to reduce an iterable to a single value. Quoting functools.reduce
,
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.
So, list comprehension cannot be used as a drop-in replacement for reduce
.
这篇关于列表理解可替代Python中的reduce()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!