【发布时间】:2015-10-29 19:56:55
【问题描述】:
我需要将两个列表合并到一个列表中并打印出来
例如:
list1 = [9, 3, 5, 7]
list2 = [5, 4 , 6]
list3 = [9, 5, 3, 4, 5, 6, 7]
我需要用“for”或“while”来做,因为我们还没有学到比这更高级的东西。
我现在的代码:
list1 = [3, 4, 5, 6]
list2 = [1, 2, 0, 9, 9]
tlist = []
n1 = len(list1)
n2 = len(list2)
n3 = n1 + n2
n4 = len(list2) - 1
n5 = len(list1) - 1
i = 1
c = 0
while i in range(0, n3):
tlist.insert(i, list1[c])
tlist.insert(i, list2[c])
c += 1
i += 2
tlist.extend(list2[n4:])
tlist.extend(list1[n5:])
for num in tlist:
print num
结果是:
3
1
4
2
5
0
6
9
9
6
(最后应该是这样的) 所以如果 len(list1) = len(list2) 我已经设法做到了 但如果列表的长度不同,它就不起作用
【问题讨论】:
-
要么你应该先写一个列表然后另一个,或者在你的循环中检查是否有任何列表已经用尽
-
您只需要任何合并,还是需要维护您正在使用的交错?
标签: python python-2.7 python-3.x