Python:两个长度相同的列表的元素连接

时间:2016-04-04 13:20:25

标签: python

我有两个长度相同的列表

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之类的替代品不会生成我想要的输出。有没有办法做得更好?

修改 谢谢您的帮助!我的清单有300,000个组件。解决方案的执行时间是

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

3 个答案:

答案 0 :(得分:10)

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 ... ]语法称为列表理解。

答案 1 :(得分: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(…)默认返回generator。如果您需要随机访问,或者您想多次迭代结果,则必须使用list(map(…))

答案 2 :(得分: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