2013-08-21 62 views
0

我有一個看起來像這樣的列表:字母領帶斷路器蟒蛇

['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46'] 

的數字代表學生的考試成績。我想使用sorted()函數在列表中排序列表,並且tie破壞者是按字母順序排列的名字。我不太熟悉這個功能,所以你的幫助將不勝感激! =)

回答

1

使用key參數與sorted(),並添加您自己的功能。

>>> L = ['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46'] 
>>> def mysort(x): 
...  temp = x.split(',') 
...  return (-int(temp[1]), temp[0]) 
... 
>>> sorted(L, key=mysort) 
['Claudia Zingaro,50', 'Ivan Connolly,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46'] 

函數被調用列表中的每個值。該函數將返回類似[46, 'Invalid Name']。然後,sorted()看到這個並根據給出的列表對其進行排序,第一個項目具有更高的優先級。

+0

+1,但你應該使用'INT(TEMP [1])'正確與1位數的得分處理。 – flornquake

+0

@flornquake確實,正在修復 – TerryA

+0

我可能會使用'temp [0] .rsplit(None,1)[:: - 1]'來獲取更多的標準名稱 –

1

您可以使用sort(key=...)函數。

試試這個:

L = ['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46'] 
L.sort(key=lambda x:int(x.split(',')[1])) 

輸出:

['Invalid Name,46', 'Cristi Authement,47', 'Yadira Millwood,47', 'Hyun Castleberry,48', 'Invalid Name,48', 'Floria Rozar,49', 'Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50'] 

很簡單明瞭。

0

與開始:

L = ['Ivan Connolly,50', 'Claudia Zingaro,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46'] 

要同時按多個鍵排序,首先,對排序的順序「輔助」鍵,你希望它是,例如,我們把它按字母順序排列忽略大小寫:

L.sort(key=str.lower) 

給我們:

['Claudia Zingaro,50', 'Cristi Authement,47', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,46', 'Invalid Name,48', 'Ivan Connolly,50', 'Jeffie Honaker,50', 'Yadira Millwood,47'] 

然後,我們按降序排序的得分字段:

L.sort(key=lambda L: int(L.rpartition(',')[2]), reverse=True) 

這讓L的最終結果:

['Claudia Zingaro,50', 'Ivan Connolly,50', 'Jeffie Honaker,50', 'Floria Rozar,49', 'Hyun Castleberry,48', 'Invalid Name,48', 'Cristi Authement,47', 'Yadira Millwood,47', 'Invalid Name,46']