Python 如何结束这个无限循环
我必须对用户输入的列表进行从低到高的排序。排序,但当我试图替换两个值以将它们按顺序排列时,我发现自己处于一个无限循环中Python 如何结束这个无限循环,python,list,sorting,loops,infinite,Python,List,Sorting,Loops,Infinite,我必须对用户输入的列表进行从低到高的排序。排序,但当我试图替换两个值以将它们按顺序排列时,我发现自己处于一个无限循环中 list = input('Enter list of numbers separated by a space: ').split() list = [int(b) for b in list] def list_sort(list): while list: a = list[0] # random number in list
list = input('Enter list of numbers separated by a space: ').split()
list = [int(b) for b in list]
def list_sort(list):
while list:
a = list[0] # random number in list
for x in list: # to check every number in the list
if x < a: # find if the new number is less than original
c, d = list.index(x), list.index(a)
list[d], list[c] = list[c], list[d]
print(list_sort(list))
您正在将while循环设置为只要list为True就运行,这在代码中总是会为True。相反,您要做的是在while循环中设置一个条件,用break语句中断循环
while True:
if some_break_condition_met:
break
else:
# do logic
此外,list在python中用于创建列表,因此我强烈建议不要使用list作为变量,可以将其更改为lst或my_list。使用列表可能会导致问题 由于您从未从列表中删除任何元素,我不知道您希望如何退出while list方法,您也不应该命名变量列表或其他内置结构。。。似乎您正在尝试实现冒泡排序。。。有许多在线解决方案可用于此
list = input('Enter list of numbers separated by a space: ').split(' ')
list = [int(b) for b in list]
def list_sort(list):
updated = True
while updated:
updated = False
for orig_index in range(0, len(list)):
for check_index in range(orig_index, len(list)):
if list[check_index] < list[orig_index]:
list[orig_index], list[check_index] = list[check_index], list[orig_index]
updated = True
print(list_sort(list))