小编Jmu*_*uru的帖子

为什么在合并两个排序列表时会得到两个不同的输出(Python)

我很困惑为什么在更改关系运算符时我得到两个不同的输出:

这是不正确的版本:

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
Run Code Online (Sandbox Code Playgroud)

输出是: [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
Run Code Online (Sandbox Code Playgroud)

我将运算符更改为<和弹出的元素的顺序,我得到此输出:

[1, 2, 3, 4, 5, …
Run Code Online (Sandbox Code Playgroud)

python algorithm merge sorted

3
推荐指数
1
解决办法
67
查看次数

标签 统计

algorithm ×1

merge ×1

python ×1

sorted ×1