简体   繁体   English

如何结束这个无限循环

[英]How to end this infinite loop

I have to sort a user inputed list from lowest to highest without . 我必须对用户输入的列表从最低到最高排序,不进行排序。 sort, but when I try to replace two values to put them in order I find myself in an infinite loop 排序,但是当我尝试替换两个值以使其按顺序排列时,我发现自己陷入了无限循环

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))

You are setting your while loop to run as long as list is True, which in your code is always going to be true. 只要将list设置为True,即可将while循环设置为运行,而在代码中,list始终为true。 What you want to do instead is set up a condition inside your while loop to break out of your loop with a break statement. 相反,您要做的是在while循环中设置一个条件,以使用break语句退出循环。

while True: 
 if some_break_condition_met:
     break
 else:
     # do logic

Also, list is used in python to create a list, so I strongly suggest not using list as your variable, maybe change it to lst or my_list. 此外,list在python中用于创建列表,因此我强烈建议不要将list用作变量,也许将其更改为lst或my_list。 Using list could cause problems. 使用列表可能会导致问题。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM