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

2024-10-16 17:18:21 发布

您现在位置: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

输出为: [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]

为什么第二个版本与第一个版本不同,正确地合并了两个列表?你知道吗


Tags: and版本l1outputifdef运算符pop
3条回答

在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);

为什么不使用:

>>> 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]

两种解决方案实际上都是错误的。第二个恰好适用于您的特定输入。你知道吗

它们是错误的,因为您首先检查某个元素是否比其他列表中的同一索引元素小,然后添加较小的元素,但随后也添加其他列表中的元素,而不检查第一个列表中的下一个索引元素是否小。你知道吗

这是第一种方法不起作用的主要原因。第二个是有效的,只针对你的特定输入-

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]

相关问题 更多 >