如何在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]
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))
用于连接列表的最常见方法是加号运算符和内置方法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]
如果使用的是NumPy,可以使用以下命令连接两个兼容维度的数组:
numpy.concatenate([a,b])
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]