如何在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]
当前回答
如果您需要使用复杂的排序规则合并两个有序列表,您可能需要像下面的代码一样自行滚动(使用简单的排序规则以提高可读性:-)。
list1 = [1,2,5]
list2 = [2,3,4]
newlist = []
while list1 and list2:
if list1[0] == list2[0]:
newlist.append(list1.pop(0))
list2.pop(0)
elif list1[0] < list2[0]:
newlist.append(list1.pop(0))
else:
newlist.append(list2.pop(0))
if list1:
newlist.extend(list1)
if list2:
newlist.extend(list2)
assert(newlist == [1, 2, 3, 4, 5])
其他回答
提供的解决方案仅针对单个列表。如果列表中有列表,并且需要合并相应的列表,则通过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]
使用简单的列表理解:
joined_list = [item for list_ in [list_one, list_two] for item in list_]
它具有使用Additional Unpacking Generalization的最新方法的所有优点-即,您可以以这种方式连接任意数量的不同可迭代项(例如,列表、元组、范围和生成器)-并且它不限于Python 3.5或更高版本。
我能找到的加入列表的所有可能方法
import itertools
A = [1,3,5,7,9] + [2,4,6,8,10]
B = [1,3,5,7,9]
B.append([2,4,6,8,10])
C = [1,3,5,7,9]
C.extend([2,4,6,8,10])
D = list(zip([1,3,5,7,9],[2,4,6,8,10]))
E = [1,3,5,7,9]+[2,4,6,8,10]
F = list(set([1,3,5,7,9] + [2,4,6,8,10]))
G = []
for a in itertools.chain([1,3,5,7,9], [2,4,6,8,10]):
G.append(a)
print("A: " + str(A))
print("B: " + str(B))
print("C: " + str(C))
print("D: " + str(D))
print("E: " + str(E))
print("F: " + str(F))
print("G: " + str(G))
输出
A: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
B: [1, 3, 5, 7, 9, [2, 4, 6, 8, 10]]
C: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
D: [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
E: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
F: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
G: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
可以使用集合获取唯一值的合并列表
mergedlist = list(set(listone + listtwo))
还可以使用itertools.chain()创建一个生成器,简单地迭代两个列表中的项目。这允许您将列表(或任何可迭代的)链接在一起进行处理,而无需将项目复制到新列表:
import itertools
for item in itertools.chain(listone, listtwo):
# Do something with each list item