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

例子:

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

预期结果:

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

当前回答

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

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]

其他回答

使用+运算符组合列表:

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

joinedlist = listone + listtwo

输出:

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

我假设您需要以下两种方法之一:

保留重复元素

这很容易。就像字符串一样连接:

def concat_list(l1,l2):
    l3 = l1+l2
    return l3

接下来,如果要消除重复元素

def concat_list(l1,l2):
   l3 = []
   for i in [l1,l2]:
     for j in i:
       if j not in l3:
         # Check if element exists in final list, if no then add element to list
         l3.append(j)
   return l3

可以使用集合获取唯一值的合并列表

mergedlist = list(set(listone + listtwo))

你也可以使用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]将按预期工作。

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

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