本文介绍了列表理解可替代Python中的reduce()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 06:50