如何在Python中连接两个列表?

例子:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

预期结果:

>>> joinedlist
[1, 2, 3, 4, 5, 6]

当前回答

如果使用的是NumPy,可以使用以下命令连接两个兼容维度的数组:

numpy.concatenate([a,b])

其他回答

您还可以使用list.exextend()方法将列表添加到另一个列表的末尾:

listone = [1,2,3]
listtwo = [4,5,6]

listone.extend(listtwo)

如果要保持原始列表的完整性,可以创建一个新的列表对象,并将两个列表都扩展到该对象:

mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)

这很简单,我认为它甚至在教程中显示了:

>>> listone = [1,2,3]
>>> listtwo = [4,5,6]
>>>
>>> listone + listtwo
[1, 2, 3, 4, 5, 6]

组合列表列表的一种非常简洁的方法是

list_of_lists = [[1,2,3], [4,5,6], [7,8,9]]
reduce(list.__add__, list_of_lists)

这给了我们

[1, 2, 3, 4, 5, 6, 7, 8, 9]
 a = [1, 2, 3]
 b = [4, 5, 6]
     
 c = a + b
 print(c)

输出

>>> [1, 2, 3, 4, 5, 6]

在上面的代码中,“+”运算符用于将两个列表连接成一个列表。

另一种解决方案

 a = [1, 2, 3]
 b = [4, 5, 6]
 c = [] # Empty list in which we are going to append the values of list (a) and (b)

 for i in a:
     c.append(i)
 for j in b:
     c.append(j)

 print(c)

输出

>>> [1, 2, 3, 4, 5, 6]

另一种方式:

>>> listone = [1, 2, 3]
>>> listtwo = [4, 5, 6]
>>> joinedlist = [*listone, *listtwo]
>>> joinedlist
[1, 2, 3, 4, 5, 6]
>>>