【问题标题】:Python : How to stop while loop while sorting list?Python:排序列表时如何停止while循环?
【发布时间】:2021-01-03 16:19:23
【问题描述】:

我正在编写代码来对列表中的元素进行排序,我实现了它但无法停止 while 循环。

当列表中的所有元素都排序后,我想停止 while 循环。

代码:

a = [27,21,22,1,11,23,0]
n=len(a)
while True:
    for i in range(n-1):
        if a[i]>a[i+1]:
            temp = a[i]
            a[i] = a[i+1]
            a[i+1] = temp
    print(a)

输出:

[21, 22, 1, 11, 23, 0, 27] [21, 1, 11, 22, 0, 23, 27] [1, 11, 21, 0, 22, 23, 27] [1, 11, 0, 21, 22, 23, 27] [1, 0, 11, 21, 22, 23, 27] [0, 1, 11, 21, 22, 23, 27] [0, 1, 11, 21, 22, 23, 27] [0, 1, 11, 21, 22, 23, 27] [0, 1, 11, 21, 22, 23, 27]........

我知道排序列表上有 10 个问答,但我只想以这种方式实现(如果可能的话)。

谁能帮我停止这个while循环?

【问题讨论】:

标签: python list sorting data-structures


【解决方案1】:

也许比 chepner 的效率高一点,每次交换都没有额外的分配,而是使用temp 来检测是否有变化:

a = [27,21,22,1,11,23,0]
n = len(a)
dummy = object()
while True:
    temp = dummy
    for i in range(n-1):
        if a[i]>a[i+1]:
            temp = a[i]
            a[i] = a[i+1]
            a[i+1] = temp
    if temp is dummy:
        break
    print(a)

【讨论】:

    【解决方案2】:

    为什么不只是:

    a = sorted(a)
    

    好吧,如果你想这样做:

    a = [27,21,22,1,11,23,0]; a_bis = []
    n=len(a)
    while a_bis != a:
        a_bis = a.copy()
        for i in range(n-1):
            if a[i]>a[i+1]:
                temp = a[i]
                a[i] = a[i+1]
                a[i+1] = temp
        
        print(a)
    

    基本上一旦有 a_bis = a 就表示上一个循环没有排序,所以 a 必须排序后才可以退出

    【讨论】:

      【解决方案3】:

      您必须跟踪a[i] > a[i+1] 是否为真。如果没有,您的列表已排序,您可以跳出循环。

      a = [27,21,22,1,11,23,0]
      n = len(a)
      while True:
          stop = True
          for i in range(n-1):
              if a[i]>a[i+1]:
                  stop = False
                  # a[i], a[i+1] = a[i+1], a[i]
                  temp = a[i]
                  a[i] = a[i+1]
                  a[i+1] = temp
          if stop:
              break

      【讨论】:

      • 只是好奇,下面你的方式和我的方式有什么不同吗?如果存在大量内存问题列表,您当然可以使用,除此之外别无他法
      • 实际上,我的stop 变量是列表比较的“预期”结果。我没有实际进行这种比较,而是“预测”它将失败,并指出任何交换都会使它失败。
      猜你喜欢
      • 2010-09-26
      • 2013-09-11
      • 2023-01-10
      • 1970-01-01
      • 2018-10-14
      • 2015-12-30
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多