gpt4 book ai didi

python - 二维数组的python总和如何返回列表

转载 作者:行者123 更新时间:2023-12-01 21:30:33 25 4
gpt4 key购买 nike

我遇到了一段 python 代码,其中二维数组的求和函数求值为列表。

例如:

a = [['a','b','c'],['d','e','f'],['g','h','i'] ]]

sum(a,[]) 返回 ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

为什么会这样?也许我遗漏了一些基本的东西,但我想了解其中的机制。

最佳答案

sum(iterable, /, start=0) :

Sums start and the items of an iterable from left to right and returns the total

因此对于您的代码,sum 产生的操作是

[] + ['a','b','c'] + ['d','e','f'] + ['g','h','i']

这是一个列表连接,并产生:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

请注意,如果您不提供 []start 值,则 sum 使用默认的 start0 并执行:

0 + ['a','b','c'] + ['d','e','f'] + ['g','h','i']

这会导致 TypeError:

TypeError: unsupported operand type(s) for +: 'int' and 'list'

关于python - 二维数组的python总和如何返回列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62605918/

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