Python 3.x python中的单层深嵌套列表求和
我尝试了以下方法Python 3.x python中的单层深嵌套列表求和,python-3.x,Python 3.x,我尝试了以下方法 a = [[1], [2]] print(sum(a)) from functools import reduce a = [[1], [2]] result = reduce(lambda first,next:first + next,a) print(result) 我期待着结果 [1, 2] 但我犯了个错误 Traceback (most recent call last): File "<stdin>", line 1, in
a = [[1], [2]]
print(sum(a))
from functools import reduce
a = [[1], [2]]
result = reduce(lambda first,next:first + next,a)
print(result)
我期待着结果
[1, 2]
但我犯了个错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:不支持+:“int”和“list”的操作数类型
这是怎么回事?我知道sum包含一个iterable,所以它不应该连接
a
中的列表元素吗?您可以使用functools
中的函数
执行以下操作
a = [[1], [2]]
print(sum(a))
from functools import reduce
a = [[1], [2]]
result = reduce(lambda first,next:first + next,a)
print(result)
这将输出
[1, 2]
我还发现,如果传递start参数,可以使用sum
方法。
像这样
a = [[1], [2]]
print(sum(a,[]))
这是因为我们的start
来自同一类型的列表项
我不知道为什么会给出错误,但我的猜测是,如果没有给出start
参数,该方法使用start等于0来对传递的iterable求和
e、 g
这将引发TypeError
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
sum(f)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
总和(f)
TypeError:不支持+:“int”和“str”的操作数类型
您可以使用functools
中的功能
执行以下操作
a = [[1], [2]]
print(sum(a))
from functools import reduce
a = [[1], [2]]
result = reduce(lambda first,next:first + next,a)
print(result)
这将输出
[1, 2]
我还发现,如果传递start参数,可以使用sum
方法。
像这样
a = [[1], [2]]
print(sum(a,[]))
这是因为我们的start
来自同一类型的列表项
我不知道为什么会给出错误,但我的猜测是,如果没有给出start
参数,该方法使用start等于0来对传递的iterable求和
e、 g
这将引发TypeError
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
sum(f)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
总和(f)
TypeError:不支持+:“int”和“str”的操作数类型
如果要使用求和
到平面列表,应使用:
a = [[1], [2]]
print(sum(a, []))
from itertools import chain
a = [[1], [2]]
print(list(chain(*a)))
结果:
[1, 2]
但是使用
sum()
将它们平铺是不好的:
连接一系列迭代,考虑使用ItRealths.Chan.() 因此,您应该使用:
a = [[1], [2]]
print(sum(a, []))
from itertools import chain
a = [[1], [2]]
print(list(chain(*a)))
并指出:“首先,不要使用sum来连接/展平列表,因为它是二次时间,因此与其他方法相比根本没有效率。它实际上使用了schlemiel the painter算法。”如果要使用
sum
来展平列表,应该使用:
a = [[1], [2]]
print(sum(a, []))
from itertools import chain
a = [[1], [2]]
print(list(chain(*a)))
结果:
[1, 2]
但是使用
sum()
将它们平铺是不好的:
连接一系列迭代,考虑使用ItRealths.Chan.() 因此,您应该使用:
a = [[1], [2]]
print(sum(a, []))
from itertools import chain
a = [[1], [2]]
print(list(chain(*a)))
并指出:“首先,永远不要使用sum来连接/展平列表,因为它是二次时间,因此与其他方法相比根本没有效率。它实际上使用了schlemiel-the-painter算法。”