2016-03-04 138 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

由於您使用的是字符串列表而不是整數列表,因此輸出錯誤。在處理列表之前,將您的字符串列表轉換爲整數列表。