2017-01-27 50 views
2

我嘗試使用同一問題中接受的解決方案中描述的方法對給定here的數據進行排序。我列出了列表的列表,並嘗試使用sorted方法嘗試排序兩次,而不是列表。但它沒有奏效。我需要與上面鏈接中給出的輸出相同的輸出。這裏是我的輸出:基於文件數據的兩個字段的Python排序

[['k3', '9.2603346875', '0.4639390435'], 
['K1', '4.1458078125', '0.5129700421'], 
['k2', '9.5360690625', '0.5481493305'], 
['k7', '9.8022878125', '0.562983695'], 
['k2', '6.319044375', '0.6469451082'], 
['k5', '7.2702040625', '0.6632701035'], 
['K1', '8.6394253125', '0.6690271589'], 
['K1', '8.025495625', '0.7561548244'], 
['k8', '5.44912125', '0.8532092538'], 
['k6', '7.73398625', '1.017231759'], 
['K1', '6.66228125', '1.0444456163'], 
['k4', '10.6868384375', '1.1287761798'], 
['k9', '7.5859665625', '1.276779643'], 
['K1', '6.48153375', '1.4176140292']] 

這裏是我的代碼:

path = "C:\\Chandresh_WORK\\data\\" 
inpfile = 'demo1.txt' 
mylist=[] 
from operator import itemgetter 
with open(path+inpfile,'r') as fid: 
    for line in fid:  
     myset = list(line.split()) 
     mylist.append(myset) 

mylist 
s=sorted(mylist,key=itemgetter(0))  
sorted(s,key=itemgetter(2)) 

回答

2

你需要投你串數字類型,以避免的逐一排序,然後反轉第二順序排序標準,使其下降:

s = sorted(mylist,key=lambda x: (x[0], -float(x[2]))) 
#         ^invert sort order 

[['K1', '6.48153375', '1.4176140292'], 
['K1', '6.66228125', '1.0444456163'], 
['K1', '8.025495625', '0.7561548244'], 
['K1', '8.6394253125', '0.6690271589'], 
['K1', '4.1458078125', '0.5129700421'], 
['k2', '6.319044375', '0.6469451082'], 
['k2', '9.5360690625', '0.5481493305'], 
['k3', '9.2603346875', '0.4639390435'], 
['k4', '10.6868384375', '1.1287761798'], 
['k5', '7.2702040625', '0.6632701035'], 
['k6', '7.73398625', '1.017231759'], 
['k7', '9.8022878125', '0.562983695'], 
['k8', '5.44912125', '0.8532092538'], 
['k9', '7.5859665625', '1.276779643']] 
+0

小號o,是否意味着如果我正確理解了第一條語句,則詞典排序會覆蓋數字類型? – chandresh

+0

如果您沒有轉換爲數字類型(使用'float'),則項目將按字符串排序 –