如何结束这个无限循环

时间:2015-10-04 01:32:21

标签: 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
        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))

2 个答案:

答案 0 :(得分:0)

只要list为True,您就设置while循环运行,在代码中始终为true。您要做的是在while循环中设置一个条件,以使用break语句突破循环。

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

此外,list在python中用于创建列表,因此我强烈建议不要使用list作为变量,也可以将其更改为lst或my_list。使用列表可能会导致问题。

答案 1 :(得分:0)

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