如何在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]
当前回答
您可以使用在列表对象上定义的append()方法:
mergedlist =[]
for elem in listone:
mergedlist.append(elem)
for elem in listtwo:
mergedlist.append(elem)
其他回答
我推荐三种方法连接列表,但最推荐第一种方法,
# 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循环来连接列表。所以时间复杂度比其他两种方法要高得多。
这个问题直接询问加入两个列表。然而,即使您正在寻找一种连接多个列表的方法(包括连接零个列表的情况),它在搜索中也非常高。
我认为最好的选择是使用列表综合:
>>> a = [[1,2,3], [4,5,6], [7,8,9]]
>>> [x for xs in a for x in xs]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
还可以创建生成器:
>>> map(str, (x for xs in a for x in xs))
['1', '2', '3', '4', '5', '6', '7', '8', '9']
旧答案
考虑这种更通用的方法:
a = [[1,2,3], [4,5,6], [7,8,9]]
reduce(lambda c, x: c + x, a, [])
将输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
注意,当a为[]或[[1,2,3]]时,这也可以正常工作。
然而,使用itertools可以更有效地实现这一点:
a = [[1,2,3], [4,5,6], [7,8,9]]
list(itertools.chain(*a))
如果您不需要列表,而只需要一个可迭代的列表,请省略list()。
使现代化
Patrick Collins在评论中提出的备选方案也适用于您:
sum(a, [])
您可以使用在列表对象上定义的append()方法:
mergedlist =[]
for elem in listone:
mergedlist.append(elem)
for elem in listtwo:
mergedlist.append(elem)
您可以在Python中使用union()函数。
joinedlist = union(listone, listtwo)
print(joinedlist)
从本质上讲,它是删除两个列表中每个重复项中的一个。因为您的列表没有任何重复项,所以它只返回两个列表的连接版本。
对于列表数量较少的情况,您可以简单地将列表添加到一起或使用就地解包(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)”。