我不明白为什么在更改关系运算符时会得到两个不同的输出:
以下是不正确的版本:
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
我将运算符更改为<;并按元素的顺序弹出,得到以下输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
为什么第二个版本与第一个版本不同,正确地合并了两个列表?你知道吗
在while循环中使用continue。 例如:
为什么不使用:
结果
两种解决方案实际上都是错误的。第二个恰好适用于您的特定输入。你知道吗
它们是错误的,因为您首先检查某个元素是否比其他列表中的同一索引元素小,然后添加较小的元素,但随后也添加其他列表中的元素,而不检查第一个列表中的下一个索引元素是否小。你知道吗
这是第一种方法不起作用的主要原因。第二个是有效的,只针对你的特定输入-
因为
listTwo
中的每个元素都小于listOne
中的下一个索引元素。如果不是这样的话,你会看到错误的结果。你知道吗正确的方法-
示例/演示-
相关问题 更多 >
编程相关推荐