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

例子:

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

预期结果:

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

当前回答

使用Python 3.3+,您可以从以下位置使用yield:

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

def merge(l1, l2):
    yield from l1
    yield from l2

>>> list(merge(listone, listtwo))
[1, 2, 3, 4, 5, 6]

或者,如果您希望支持任意数量的迭代器:

def merge(*iters):
    for it in iters:
        yield from it

>>> list(merge(listone, listtwo, 'abcd', [20, 21, 22]))
[1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 20, 21, 22]

其他回答

使用简单的列表理解:

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

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

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

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

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

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]

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]

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

如果要以排序形式合并这两个列表,可以使用heapq库中的merge函数。

from heapq import merge

a = [1, 2, 4]
b = [2, 4, 6, 7]

print list(merge(a, b))