在Python中合并/添加列表 [英] Merging/adding lists in Python
本文介绍了在Python中合并/添加列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我非常确定应该有一种更Python化的方法来执行此操作-但我想不出:如何将二维列表合并为一维列表?类似于zip/map,但具有两个以上的迭代器.
I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.
示例-我有以下列表:
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
我想拥有
result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9]
到目前为止,我想出的是:
So far what I've come up with is:
def add_list(array):
number_items = len(array[0])
result = [0] * number_items
for index in range(number_items):
for line in array:
result[index] += line[index]
return result
但是对我来说,这看起来并不优雅/Pythonic.除了不检查2D数组中的所有线"是否都具有相同的长度,可以相互添加等等,还有什么更好的方法呢?
But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?
推荐答案
[sum(a) for a in zip(*array)]
这篇关于在Python中合并/添加列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文