Python:两个长度相同的列表逐元素合并

11

我有两个相同长度的列表

a = [[1,2], [2,3], [3,4]]
b = [[9], [10,11], [12,13,19,20]]

并且想要将它们合并

c = [[1, 2, 9], [2, 3, 10, 11], [3, 4, 12, 13, 19, 20]]

我通过这样做来实现

c= []
for i in range(0,len(a)):
    c.append(a[i]+ b[i])

然而,我习惯于使用R来避免for循环,而类似zip和itertools的替代方法无法产生我所需的输出。有更好的方法吗?

编辑:感谢帮助!我的列表有30万个元素。这些解决方案的执行时间为:

[a_ + b_ for a_, b_ in zip(a, b)] 
1.59425 seconds
list(map(operator.add, a, b))
2.11901 seconds
3个回答

16

Python有一个内置的zip函数,我不确定它与R中的相似程度如何,您可以像这样使用它

a_list = [[1,2], [2,3], [3,4]]
b_list = [[9], [10,11], [12,13]]
new_list = [a + b for a, b in zip(a_list, b_list)]

如果您想了解更多,[ ... for ... in ... ] 语法称为列表推导。


谢谢。我选择了这个答案,因为在我的数据集上速度更快。作为一个 Python 新手,我没有其他的标准可供参考。 - HOSS_JFL

9
>>> help(map)
map(...)
    map(function, sequence[, sequence, ...]) -> list

    Return a list of the results of applying the function to the items of
    the argument sequence(s).  If more than one sequence is given, the
    function is called with an argument list consisting of the corresponding
    item of each sequence, substituting None for missing values when not all
    sequences have the same length.  If the function is None, return a list of
    the items of the sequence (or a list of tuples if more than one sequence).

正如您所见,map(…)可以将多个可迭代对象作为参数。

>>> import operator
>>> help(operator.add)
add(...)
    add(a, b) -- Same as a + b.

所以:
>>> import operator
>>> map(operator.add, a, b)
[[1, 2, 9], [2, 3, 10, 11], [3, 4, 12, 13]]

请注意,在Python 3中,map(…)默认返回一个生成器。如果您需要随机访问或者想要多次迭代结果,则必须使用list(map(…))

0
你可以这样做:
>>> [x+b[i] for i,x in enumerate(a)]
[[1, 2, 9], [2, 3, 10, 11], [3, 4, 12, 13, 19, 20]]

要合并两个列表,在Python中非常容易:

mergedlist = listone + listtwo

你的第二行代码有误导性,与问题无关。或许可以删除它?你的第一行代码是对问题的很好回答(而且这种方法也可以轻松应用于其他数据类型,不仅仅是数字)。 - Borislav Aymaliev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接