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