如何在Python中连接两个列表?
例子:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
预期结果:
>>> joinedlist
[1, 2, 3, 4, 5, 6]
如何在Python中连接两个列表?
例子:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
预期结果:
>>> joinedlist
[1, 2, 3, 4, 5, 6]
当前回答
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
输出
>>> [1, 2, 3, 4, 5, 6]
在上面的代码中,“+”运算符用于将两个列表连接成一个列表。
另一种解决方案
a = [1, 2, 3]
b = [4, 5, 6]
c = [] # Empty list in which we are going to append the values of list (a) and (b)
for i in a:
c.append(i)
for j in b:
c.append(j)
print(c)
输出
>>> [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]
对于列表数量较少的情况,您可以简单地将列表添加到一起或使用就地解包(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)”。
还可以使用itertools.chain()创建一个生成器,简单地迭代两个列表中的项目。这允许您将列表(或任何可迭代的)链接在一起进行处理,而无需将项目复制到新列表:
import itertools
for item in itertools.chain(listone, listtwo):
# Do something with each list item
我假设您需要以下两种方法之一:
保留重复元素
这很容易。就像字符串一样连接:
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
你也可以使用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]将按预期工作。