2016-09-22 95 views
0

這裏是我完整的代碼示例:在python排序不工作

import csv 
import operator 

f=open('C://Users//ganesha//Desktop//b//sampleDataCsv.csv',"r") 
readerObject1 = csv.reader(f,delimiter = ",")  
inputList = list(readerObject1)  
print("Input",inputList) 

sortedList = sorted(inputList,key=operator.itemgetter(0),reverse=True) 

print("Output",sortedList) 

f1=open('C://Users//ganesha//Desktop//b//sampleDataCsv4.csv',"w+") 
writerObject=csv.writer(f1,delimiter=",",lineterminator='\n') 

writerObject.writerows(sortedList) 

我的輸入是這樣的:

[['20'], ['12'], ['13'], ['11'], ['14'], ['15'], ['19'], ['1'], ['2'], ['4'], ['9'], ['0'], ['8'], ['7'], ['5'], ['6'], ['3'], ['16'], ['17'], ['10']] 

而且我的輸出出來是這樣的:

[['9'], ['8'], ['7'], ['6'], ['5'], ['4'], ['3'], ['20'], ['2'], ['19'], ['17'], ['16'], ['15'], ['14'], ['13'], ['12'], ['11'], ['10'], ['1'], ['0']] 

回答

3

那是因爲你正在排序代表數字的str。創建一個小lambda是獲取項目並將它轉換到int基於int值來獲得一種:

k = lambda x: int(x[0])  
sortedList = sorted(inputList,key=k,reverse=True) 

現在sortedList基礎上,int值進行排序:

[['20'], ['19'], ['17'], ['16'], ['15'], ['14'], ['13'], ['12'], 
['11'], ['10'], ['9'], ['8'], ['7'], ['6'], ['5'], ['4'], ['3'], 
['2'], ['1'], ['0']] 

如果你不」不要介意一些卷積,將lambda直接放在呼叫sorted

sortedList = sorted(inputList, key=lambda x: int(x[0]), reverse=True) 
+3

如果僅使用一次,則在函數調用中使用lambda函數。 – Santos