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

例子:

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

预期结果:

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

当前回答

你也可以使用sum。

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> sum([a, b], [])
[1, 2, 3, 4, 5, 6]
>>>

这适用于任何长度和任何元素类型的列表:

>>> a = ['a', 'b', 'c', 'd']
>>> b = [1, 2, 3, 4]
>>> c = [1, 2]
>>> sum([a, b, c], [])
['a', 'b', 'c', 'd', 1, 2, 3, 4, 1, 2]
>>>

我添加[]的原因是,start参数默认设置为0,因此它在列表中循环并添加到start,但0+[1,2,3]会产生错误,因此如果我们将start设置为[]。它将添加到[],并且[]+[1,2,3]将按预期工作。

其他回答

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

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

listone.extend(listtwo)

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

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

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

# 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循环来连接列表。所以时间复杂度比其他两种方法要高得多。

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

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]

如果不能使用加号运算符(+),则可以使用运算符导入:

import operator

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

result = operator.add(listone, listtwo)
print(result)

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

或者,您也可以使用__add__dunder函数:

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

result = list.__add__(listone, listtwo)
print(result)

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