我很困惑为什么在更改关系运算符时我得到两个不同的输出:
以下是不正确的版本:
listOne = [1,3,6,9,11]
listTwo = [2,4,5,7,8,10,12]
def mergeTwo(l1,l2):
output = []
while l1 and l2:
if l1[0] > l2[0]:
output.append(l2.pop(0))
output.append(l1.pop(0))
if l1:
output.extend(l1)
elif l2:
output.extend(l2)
print output
输出是:
[1, 2, 3, 4, 6, 5, 9, 7, 11, 8, 10, 12]
但是当我这样做时它会起作用:
listOne = [1,3,6,9,11]
listTwo = [2,4,5,7,8,10,12]
def mergeTwo(l1,l2):
output = []
while l1 and l2:
if l1[0] < l2[0]:
output.append(l1.pop(0))
output.append(l2.pop(0))
if l1:
output.extend(l1)
elif l2:
output.extend(l2)
print output
我将运算符更改为&lt;弹出的元素的顺序,我得到这个输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
为什么第二个版本正确地合并两个列表?与第一个版本不同?
答案 0 :(得分:6)
两种解决方案实际上都是错误的。第二个恰好适合您的特定输入。
它们是错误的,因为您首先检查某个元素是否小于其他列表中的相同索引元素,然后添加较小的元素,然后再去添加其他列表中的元素,而不检查第一个列表中的下一个索引元素是否更小。
这是第一个不起作用的主要原因。第二个适用于您的特定输入 -
listOne = [1,3,6,9,11]
listTwo = [2,4,5,7,8,10,12]
因为listTwo
中的每个元素都小于listOne
中的下一个索引元素。在不是这种情况下给出输入,你会看到错误的结果。
正确的方法 -
def mergeTwo(l1,l2):
output = []
while l1 and l2:
if l1[0] < l2[0]:
output.append(l1.pop(0))
else:
output.append(l2.pop(0))
if l1:
output.extend(l1)
elif l2:
output.extend(l2)
print output
示例/演示 -
>>> listOne = [1,3,6,9,11]
>>> listTwo = [2,4,5,7,8,10,12]
>>>
>>> def mergeTwo(l1,l2):
... output = []
... while l1 and l2:
... if l1[0] < l2[0]:
... output.append(l1.pop(0))
... else:
... output.append(l2.pop(0))
... if l1:
... output.extend(l1)
... elif l2:
... output.extend(l2)
... print(output)
...
>>> mergeTwo(listOne,listTwo)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> listOne = [1,3,6,9,11]
>>> listTwo = [10,15,20,25,30]
>>> mergeTwo(listOne,listTwo)
[1, 3, 6, 9, 10, 11, 15, 20, 25, 30]
答案 1 :(得分:0)
为什么不使用:
>>> listOne = [1,3,6,9,11]
>>> listTwo = [2,4,5,7,8,10,12]
>>> merge = listOne + listTwo
>>> merge.sort()
结果
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
答案 2 :(得分:0)
在while循环中使用continue。 例如:
import os,sys
listOne = [1,3,6,9,11]
listTwo = [2,4,5,7,8,10,12]
def mergeTwo(l1,l2):
output = [];
while l1 and l2:
if l1[0] > l2[0]:
output.append(l2.pop(0))
continue;
output.append(l1.pop(0))
if l1:
output.extend(l1)
elif l2:
output.extend(l2)
print output
mergeTwo(listOne, listTwo);