2016-03-04 141 views
1

我正在研究一个程序,该程序需要一个列表并将其从最高到最低排序[是的,我知道我可以使用.sort()]。该方案如下:Python 2:排序算法不起作用

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']“

+1

你的值是字符串而不是整数,因此''''出现在'-40'之前 – Jaco

+3

Nitpicky与问题无关的东西,约定是以小写字母开头而不是大写 – StephenTG

回答

5

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

由于约翰尼拉表明,List = [int(x) for x in UnList.split(",")]将转换为整数

+0

当我将它改为'''List = int(UnList.split(“,”))'''我得到了错误:TypeError:int()参数必须是一个字符串或一个数字,而不是'list' .py'''显然我做错了什么,但我不确定是什么。谢谢。 – TheRIProgrammer

+2

在UnList.split(“,”)]中列表= [int(x)] – Johny

+1

@TheRIProgrammer您尝试将整个列表转换为单个整数。 Johny的方式应该单独转换每个元素 – StephenTG

2

您需要将您的值转换成整数列表的一种方式,否则他们不得到正确排序。你可以通过修改代码分割字符串行做到这一点:

List = map(int,UnList.split(",")) #Turns the users numbers into a list 

此更改后,输出为:

[-40, -10, 2, 2, 3, 4, 4, 5] 

这是我的全码:

UnList = '-10, -40, 2, 2, 3, 4, 4, 5' 
List = map(int,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

由于您使用的是字符串列表而不是整数列表,因此输出错误。在处理列表之前,将您的字符串列表转换为整数列表。