python 2 : Sorting algorithm does not work

标签 python sorting

我正在开发一个程序,它接受一个列表并将其从最高到最低排序 [是的,我知道我可以使用 .sort()]。程序如下:

UnList = raw_input("Enter a list of numbers seperated by commas") #collects the users list
List = UnList.split(",") #Turns the users numbers into a list
for x in range(len(List)): #number of time to sort
  Switcher = 0 #the switcher (also will reset it later)
  for z in range(len(List)-1): #number of time the switcher runs
    if List[Switcher] > List[(Switcher + 1)]: #if one number is bigger than the other
      List[Switcher],List[(Switcher+1)] = List[(Switcher+1)],List[Switcher] #this switches those 2 numbers
    Switcher += 1 #adds to the switcher
print "The new list is:", List #prints the output

有时它会起作用,例如“1,7,4,6​​,3” 其他时候,例如“-10,5,4,32,4,-40,2”,它会给出完全不正确的输出“['-10', '-40', '2', '32', ' 4', '4', '5']"

最佳答案

根据您得到的顺序,我认为问题可能是排序是按字典顺序进行的,而不是数字顺序。确保所有元素都作为整数而不是字符串进行比较

正如 Johny 所建议的,List = [int(x) for x in UnList.split(",")] 是一种转换为整数列表的方法

关于 python 2 : Sorting algorithm does not work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35798292/

相关文章:

python - 如何在不使用 Ordereddict 的情况下按键对 Python 字典进行排序?

python - 导入错误 : No module named http django

python - 根据圆的面积更改 numpy 数组中的值

python - Pandas 从 str.extractall ('#' 给出错误)

python - 如果 Django ORM 要使用错误的 PK 值,是否需要自定义 ForeignKey 子类?

javascript - 排序或部分排序最小化比较

python - 模块未找到错误: No module named 'neo4j.addressing' and ModuleNotFoundError: No module named 'neo4j'

algorithm - 适用于排序列表的排序算法

javascript - 在 JS 中对数组进行排序和过滤

algorithm - 二叉搜索树与排序双向链表