gpt4 book ai didi

python - 列表推导代替 Python 中的 reduce()

转载 作者:IT老高 更新时间:2023-10-28 20:48:09 25 4
gpt4 key购买 nike

下面的python教程说:

List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce().

http://python-course.eu/python3_list_comprehension.php

但是,它没有提到列表推导如何替代 reduce() 的示例,我想不出应该如何实现的示例。

能否请人解释一下如何通过列表理解实现类似 reduce 的功能或确认它是不可能的?

最佳答案

理想情况下,列表理解是创建一个新列表。报价 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.

reduce 用于将可迭代对象缩减为单个值。报价 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.

因此,列表推导式不能用作 reduce 的直接替代品。

关于python - 列表推导代替 Python 中的 reduce(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34586127/

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