python - 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, 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循环?
解决方案
也许比 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)
推荐阅读
- dataframe - 从数据框中选择列
- typescript - 无法使用 React Native/Typescript 从 Firebase 集合加载数据
- javascript - 为什么更改 CSS 属性的基值会禁用悬停激活?
- c++ - Direct2D如何正确绘制文字并实现轮廓效果
- python - 启动 discord.py 机器人时出现错误
- java - 使用 Springboot 从 sql 数据库下载图像文件
- reactjs - 我正在尝试创建一个 react.js 项目,但在我的每个关于 index.js 文件的项目中都发生了同样的错误,如何解决这个错误?
- python - 寻找一种更快的方法来替换 pandas DatetimeIndex 中的年份
- google-apps-script - 初学者问题自定义谷歌助手操作
- asp.net-core - 从 ASP.NET Core 1.0 直接迁移到 ASP.NET Core 3.1