如何在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]
当前回答
我假设您需要以下两种方法之一:
保留重复元素
这很容易。就像字符串一样连接:
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
其他回答
使用+运算符组合列表:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
joinedlist = listone + listtwo
输出:
>>> joinedlist
[1, 2, 3, 4, 5, 6]
另一种方式:
>>> listone = [1, 2, 3]
>>> listtwo = [4, 5, 6]
>>> joinedlist = [*listone, *listtwo]
>>> joinedlist
[1, 2, 3, 4, 5, 6]
>>>
您可以使用在列表对象上定义的append()方法:
mergedlist =[]
for elem in listone:
mergedlist.append(elem)
for elem in listtwo:
mergedlist.append(elem)
提供的解决方案仅针对单个列表。如果列表中有列表,并且需要合并相应的列表,则通过for循环执行“+”操作即可。
a = [[1,2,3], [4,5,6]]
b = [[0,1,2], [7,8,9]]
for i in range(len(a)):
cc.append(a[i] + b[i])
输出:[[1,2,3,0,1,2],[4,5,6,7,8,9]
您还可以使用list.exextend()方法将列表添加到另一个列表的末尾:
listone = [1,2,3]
listtwo = [4,5,6]
listone.extend(listtwo)
如果要保持原始列表的完整性,可以创建一个新的列表对象,并将两个列表都扩展到该对象:
mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)