如何在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,例如:
list = [1,2]
list = list + [3]
# list = [1,2,3]
list.append(3)
# list = [1,2,3]
list.append([3,4])
# list = [1,2,[3,4]]
对于大多数情况,这都会起作用,但如果添加了列表,append函数将不会扩展列表。因为这是不期望的,所以可以使用另一个名为extend的方法。它应适用于以下结构:
list = [1,2]
list.extend([3,4])
# list = [1,2,3,4]
其他回答
可以使用集合获取唯一值的合并列表
mergedlist = list(set(listone + listtwo))
另一种方式:
>>> listone = [1, 2, 3]
>>> listtwo = [4, 5, 6]
>>> joinedlist = [*listone, *listtwo]
>>> 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))
您可以简单地使用+或+=运算符,如下所示:
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
Or:
c = []
a = [1, 2, 3]
b = [4, 5, 6]
c += (a + b)
此外,如果希望合并列表中的值是唯一的,可以执行以下操作:
c = list(set(a + b))
我推荐三种方法连接列表,但最推荐第一种方法,
# 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循环来连接列表。所以时间复杂度比其他两种方法要高得多。