list_a = [1,7,9,35,36,37]
list_b = [3,4,5,40]
预期产出:
list_merged = [1,3,4,5,7,9,35,36,37,40]
我知道zip
的作用如下,并且完全符合我的要求。
>>> x = [1, 2]
>>> y = [1, 3, 4, 5, 6]
>>> zip(x,y)
[(1, 1), (2, 3)]
>>> zip(y, x)
[(1, 1), (3, 2)]
答案 0 :(得分:1)
这是我自己尝试的。解决方案并不是很短,但简单 ..
def linear_merge(list1, list2):
i = 0
j = 0
list_m = [] # resultant list
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]: #take element from list 1
list_m.append(list1[i])
i += 1
else: # or take element from list 2
list_m.append(list2[j])
j += 1
if i <= len(list1) - 1: #append remaing elements from list 1
list_m.extend(list1[i:])
elif j <= len(list2) - 1: #or append remaing elements from list 2
list_m.extend(list2[j:])
return list_m
这对我来说是第一手,似乎是C方式。还有 pythonic 解决方案?
答案 1 :(得分:0)
您可以使用不同的索引变量遍历两个列表。
list_a = [1,7,9,35,36,37]
list_b = [3,4,5,40]
index_a = 0
index_b = 0
merged = []
while index_a<len(list_b) or index_b < len(list_b):
if index_a<len(list_a) and list_a[index_a]<=list_b[index_b]:
merged.append(list_a[index_a])
index_a +=1
elif index_b<len(list_b):
merged.append(list_b[index_b])
index_b +=1
print merged
# [1, 3, 4, 5, 7, 9, 35, 36, 37, 40]
答案 2 :(得分:0)
方法是:
为每个列表保留两个指针(对于列表的索引)并检查较小的元素。找到较小的元素时,移动该列表的指针下一个元素。保持另一个(第二个列表)指针不变。因此,每个列表只能遍历一次。如果你实现上述方法,那么你唯一想念的就是那个最大的(最后一个)元素。因此,还有一个指针用于保留最后一个元素。
希望这会有所帮助:
list_a = [1,7,9,35,36,37] # also works for list_a = [1,7,9,35,36,45]
list_b = [3,4,5,40]
ptr_a = 0 # pointer for a
ptr_b = 0 # pointer for b
last = 0 # pointer for last element
list_merged = [] # merged result list
while ptr_a<len(list_a) and ptr_b<len(list_b):
if list_a[ptr_a] < list_b[ptr_b]:
list_merged.append(list_a[ptr_a])
ptr_a = ptr_a + 1
last = list_b[ptr_b] # assign last element
else:
list_merged.append(list_b[ptr_b])
ptr_b = ptr_b + 1
last = list_a[ptr_a] # assign last element
# at the end of the while loop the last element of
# the 'merged list' has not added. Below line is to add it.
list_merged.append(last)
print list_merged
答案 3 :(得分:0)
合并两个列表的最简单方法是使用' + '运算符作为两个
list1 = [1,2,3]
list2 = [4,5,6]
list3 = list1+list2
#This merges both lists and puts them in list3
使用以下代码: -
list3 = [ ]
for i in list1:
list3.append(i);
for i in list2:
list3.append(i) ;
现在list3将有合并的结果。
我应该如何警告你,第一种pythonic方式几乎比第二种方式快3倍。 (刚用timeit模块测试)