gpt4 book ai didi

python - 使用 map 对 list 的元素求和

转载 作者:行者123 更新时间:2023-11-28 19:42:25 26 4
gpt4 key购买 nike

我想知道是否可以使用 map 对列表的元素求和。

假设 a = [1, 2, 3, 4]

list(map(sum, a)) 会报错 int object is not iterable 因为 list 需要 iterables。

map(sum, a) 是一个有效的语句,但是给定了对象,我没有看到取消引用它的简单方法。

[map(sum, a)] 将返回列表中的一个对象

this回答说这应该很容易。我在这里缺少什么?

最佳答案

map 对列表中的每个元素应用一个函数。相反,您可以使用 reduce:

a = [1, 2, 3, 4]
sum_a = reduce(lambda x, y:x+y, a)

在这种情况下,可以使用纯粹的sum,但是,为了更实用,reduce 是更好的选择。

或者,在 Python3 中:

from functools import reduce
a = [1, 2, 3, 4]
sum_a = reduce(lambda x, y:x+y, a)

关于python - 使用 map 对 list 的元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47927234/

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