Skip to main content
 首页 » 编程设计

python 2 : Sorting algorithm does not work

2025年05月04日9emanlee

我正在开发一个程序,它接受一个列表并将其从最高到最低排序 [是的,我知道我可以使用 .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(",")] 是一种转换为整数列表的方法