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

例子:

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

预期结果:

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

其他回答

list(set(listone) | set(listtwo))

上述代码不保留顺序,并从每个列表中删除重复项(但不从连接列表中删除)。

使用+运算符组合列表:

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

joinedlist = listone + listtwo

输出:

>>> 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]将按预期工作。

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

值得注意的是,itertools.chain函数接受可变数量的参数:

>>> l1 = ['a']; l2 = ['b', 'c']; l3 = ['d', 'e', 'f']
>>> [i for i in itertools.chain(l1, l2)]
['a', 'b', 'c']
>>> [i for i in itertools.chain(l1, l2, l3)]
['a', 'b', 'c', 'd', 'e', 'f']

如果输入是可迭代的(元组、列表、生成器等),则可以使用from_iteable类方法:

>>> il = [['a'], ['b', 'c'], ['d', 'e', 'f']]
>>> [i for i in itertools.chain.from_iterable(il)]
['a', 'b', 'c', 'd', 'e', 'f']