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

例子:

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

预期结果:

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

当前回答

提供的解决方案仅针对单个列表。如果列表中有列表,并且需要合并相应的列表,则通过for循环执行“+”操作即可。

a = [[1,2,3], [4,5,6]]

b = [[0,1,2], [7,8,9]]

for i in range(len(a)):
    cc.append(a[i] + b[i])

输出:[[1,2,3,0,1,2],[4,5,6,7,8,9]

其他回答

还可以使用itertools.chain()创建一个生成器,简单地迭代两个列表中的项目。这允许您将列表(或任何可迭代的)链接在一起进行处理,而无需将项目复制到新列表:

import itertools
for item in itertools.chain(listone, listtwo):
    # Do something with each list item

提供的解决方案仅针对单个列表。如果列表中有列表,并且需要合并相应的列表,则通过for循环执行“+”操作即可。

a = [[1,2,3], [4,5,6]]

b = [[0,1,2], [7,8,9]]

for i in range(len(a)):
    cc.append(a[i] + b[i])

输出:[[1,2,3,0,1,2],[4,5,6,7,8,9]

您可以简单地使用+或+=运算符,如下所示:

a = [1, 2, 3]
b = [4, 5, 6]

c = a + b

Or:

c = []
a = [1, 2, 3]
b = [4, 5, 6]

c += (a + b)

此外,如果希望合并列表中的值是唯一的,可以执行以下操作:

c = list(set(a + b))

我能找到的加入列表的所有可能方法

import itertools

A = [1,3,5,7,9] + [2,4,6,8,10]

B = [1,3,5,7,9]
B.append([2,4,6,8,10])

C = [1,3,5,7,9]
C.extend([2,4,6,8,10])

D = list(zip([1,3,5,7,9],[2,4,6,8,10]))
E = [1,3,5,7,9]+[2,4,6,8,10]
F = list(set([1,3,5,7,9] + [2,4,6,8,10]))

G = []
for a in itertools.chain([1,3,5,7,9], [2,4,6,8,10]):
    G.append(a)


print("A: " + str(A))
print("B: " + str(B))
print("C: " + str(C))
print("D: " + str(D))
print("E: " + str(E))
print("F: " + str(F))
print("G: " + str(G))

输出

A: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
B: [1, 3, 5, 7, 9, [2, 4, 6, 8, 10]]
C: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
D: [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
E: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
F: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
G: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

我推荐三种方法连接列表,但最推荐第一种方法,

# Easiest and least complexity method <= recommended

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

newlist = listone + listtwo
print(newlist)

# Second-easiest method
newlist = listone.copy()
newlist.extend(listtwo)
print(newlist)

在第二个方法中,我将newlist分配给listone的副本,因为我不想更改listone。

# Third method
newlist = listone.copy()
for j in listtwo:
    newlist.append(j)

print(newlist)

这不是连接列表的好方法,因为我们正在使用for循环来连接列表。所以时间复杂度比其他两种方法要高得多。