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

例子:

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

预期结果:

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

当前回答

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

from heapq import merge

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

print list(merge(a, b))

其他回答

对于列表数量较少的情况,您可以简单地将列表添加到一起或使用就地解包(Python-3.5+版本中提供):

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

In [2]: listone + listtwo                                                                                                                                                                                   
Out[2]: [1, 2, 3, 4, 5, 6]
                                                                                                                                                                                     
In [3]: [*listone, *listtwo]                                                                                                                                                                                
Out[3]: [1, 2, 3, 4, 5, 6]

对于列表数量较多的情况,可以使用itertools模块中的chain.from_iterable()1函数,这是一种更通用的方法。此外,根据这个答案,这个函数是最好的;或者至少是一种非常好的方式来展开嵌套列表。

>>> l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> import itertools
>>> list(itertools.chain.from_iterable(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

1.注意,“chain.from_iterable()”在Python 2.6及更高版本中可用。在其他版本中,使用“chain(*l)”。

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

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

使用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]

另一种方式:

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

使用+运算符组合列表:

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

joinedlist = listone + listtwo

输出:

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