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

例子:

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

预期结果:

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

当前回答

使用简单的列表理解:

joined_list = [item for list_ in [list_one, list_two] for item in list_]

它具有使用Additional Unpacking Generalization的最新方法的所有优点-即,您可以以这种方式连接任意数量的不同可迭代项(例如,列表、元组、范围和生成器)-并且它不限于Python 3.5或更高版本。

其他回答

您可以使用在列表对象上定义的append()方法:

mergedlist =[]
for elem in listone:
    mergedlist.append(elem)
for elem in listtwo:
    mergedlist.append(elem)

使用+运算符组合列表:

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

joinedlist = listone + listtwo

输出:

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

如果您需要使用复杂的排序规则合并两个有序列表,您可能需要像下面的代码一样自行滚动(使用简单的排序规则以提高可读性:-)。

list1 = [1,2,5]
list2 = [2,3,4]
newlist = []

while list1 and list2:
    if list1[0] == list2[0]:
        newlist.append(list1.pop(0))
        list2.pop(0)
    elif list1[0] < list2[0]:
        newlist.append(list1.pop(0))
    else:
        newlist.append(list2.pop(0))

if list1:
    newlist.extend(list1)
if list2:
    newlist.extend(list2)

assert(newlist == [1, 2, 3, 4, 5])

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

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

Python>=3.5可选:[*l1,*l2]

通过接受PEP 448引入了另一种备选方案,值得一提。

名为Additional Unpacking Generalization的PEP在Python中使用星号*表达式时,通常会减少一些语法限制;使用它,连接两个列表(适用于任何可迭代的列表)现在也可以通过以下方式完成:

>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> joined_list = [*l1, *l2]  # unpack both iterables in a list literal
>>> print(joined_list)
[1, 2, 3, 4, 5, 6]

此功能是为Python 3.5定义的,但尚未向后移植到3.x系列的早期版本。在不支持的版本中,将引发SyntaxError。

与其他方法一样,这也会创建相应列表中元素的浅拷贝。


这种方法的好处是,你真的不需要列表来执行它;任何可迭代的都可以。如PEP中所述:

这也是一种更易读的方法,可以将可迭代项相加为列表,例如my_list+list(my_tuple)+list(my_range),现在相当于[*my_list,*my_tuple,*my_range]。

因此,虽然添加+会由于类型不匹配而引发TypeError:

l = [1, 2, 3]
r = range(4, 7)
res = l + r

以下情况不会:

res = [*l, *r]

因为它将首先解压缩可迭代内容,然后简单地从内容创建一个列表。