如何解决Python:如何在排序列表时停止while循环?
我正在编写代码来对列表中的元素进行排序,我实现了它,但无法停止 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,27] [21,27] [1,27] [0,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,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
,
也许比 chepner 的效率高一点,没有为每次交换分配额外的赋值,而是使用 temp
来检测是否有变化:
a = [27,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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。