Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:两个长度相同的列表的元素连接_Python - Fatal编程技术网

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

Python:两个长度相同的列表的元素连接,python,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等替代方案不会生成我想要

我有两张同样长的单子

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

编辑: 谢谢你的帮助!我的列表有300000个组件。解决方案的执行时间为

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

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

>>> 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(…)
可以将多个iterables作为参数

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


请注意,在Python3中,
map(…)
默认返回一个。如果您需要随机访问,或者您希望对结果进行多次迭代,那么您必须使用
list(map(…)

您可以这样做:

>>> [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

请不要只是投反对票就走开。请负责,在此处添加您的原因。您的第二行代码具有误导性。这与问题无关。也许把它拿走?您的第一行代码很好地回答了这个问题(并且可以轻松地应用于其他数据类型,而不仅仅是数字)。谢谢。我给这个答案打勾,因为它在我的数据集上更快。作为一个python noob,我没有其他标准可以依据。
mergedlist = listone + listtwo