Python 3无限循环带冒号排序

时间:2017-02-11 03:34:14

标签: python python-3.x sorting infinite-loop bubble-sort

我有一个问题,我必须对数字列表进行排序,我做得很好。但后来我要列出列表中5个最高数字的列表,我必须注意到有重复的数字。但是,当我尝试这样做时,没有任何打印。如果我尝试打印“计数”,则只会打印无限数量的增加数字。我究竟做错了什么?

list = [8,3,7,4,2,1,6,5,10,9,3,9,6,7,5]

def sortList(list):
    switch = 1
    temp = int(0)

    while (switch != 0):
        switch = 0
        for i in range(len(list)-1):
            if list[i] > list[i+1]:
                temp = list[i]
                list[i] = list[i+1]
                list[i+1] = temp
                switch = 1

#这就是我的问题所在

    count = int(0) 
    expensive5 = []

    while count != 5:

        for i in range(len(list)-1, 0, -1):
            if float(list[i]) > float(list[i-1]):
                expensive5.append(list[i])
                count += 1
                #if i print count here, I get an infinite number of increasing numbers





     print(expensive5)


sortList(list)

3 个答案:

答案 0 :(得分:0)

我建议只使用集合,然后使用切片在列表中获取所需的数字,而不是计数。

expensive5 = bubble_sort(list(set(l)))[:-6:-1]
print(expensive5)

另外,我建议不要将list用作变量名,因为它是转换为list类型的默认函数。在这里,我改为使用变量l

l = [8,3,7,4,2,1,6,5,10,9,3,9,6,7,5]

def sortList(l):
    switch = 1
    temp = int(0)

    while (switch != 0):
        switch = 0
        for i in range(len(l)-1):
            if l[i] > l[i+1]:
                temp = l[i]
                l[i] = l[i+1]
                l[i+1] = temp
                switch = 1
    return l

答案 1 :(得分:0)

您可以使用集合来仅获取列表中的唯一元素,因为列表已排序,您可以获得5个最高的数字,如下所示:

l = [8,3,7,4,2,1,6,5,10,9,3,9,6,7,5]

def bubble_sort(l):
  changed = True
  while changed:
    changed = False
    for i in range(len(l) - 1):
      if l[i] > l[i+1]:
        l[i], l[i+1] = l[i+1], l[i]
        changed = True
  return l

print(list(set(bubble_sort(l)))[-5:]) #[6, 7, 8, 9, 10]

试试here!

其他一般提示:

答案 2 :(得分:0)

问题是你的count变量第一次通过for循环传递5,所以当while循环检查其状态时,count永远不会等于5。要解决此问题,您需要将检查移动到内部循环中,如下所示:

count = int(0) 
expensive5 = []

for i in range(len(list)-1, 0, -1):
    if float(list[i]) > float(list[i-1]):
        expensive5.append(list[i])
        count += 1
        #if i print count here, I get an infinite number of increasing numbers
        if count == 5: break

print(expensive5)