Python:如何在排序列表时停止while循环?

Python:如何在排序列表时停止while循环?,python,list,sorting,data-structures,Python,List,Sorting,Data Structures,我正在编写代码来对列表中的元素进行排序,我实现了这一点,但在循环时无法停止 当列表中的所有元素都排序后,我想停止while循环 代码: 输出: [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,

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

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

代码:

输出:

[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循环吗?

为什么不:

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进行排序,然后您可以退出您必须跟踪
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
a=[27,21,22,1,11,23,0]
n=len(a)
尽管如此:
停止=正确
对于范围(n-1)内的i:
如果a[i]>a[i+1]:
停止=错误
#a[i],a[i+1]=a[i+1],a[i]
温度=a[i]
a[i]=a[i+1]
a[i+1]=温度
如果停止:

break
可能比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)

a[i]>a[i+1]
对任何
i
都不是真的时,您停止。这是否回答了您的问题?只是好奇,你的方式和我的有什么不同吗?如果出现大量内存问题的列表,您当然可以使用它,除此之外,我的
stop
变量是列表比较的“预期”结果。我并没有实际进行比较,而是“预测”它会失败,因为我注意到任何互换都会使它失败。
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)