項目編寫過程中,總能遇見對字典進行排序什么的,如果要實現多條件排序只需要下面幾行代碼實現。充分體現了python的好處了。
代碼如下:
teamitems = [{'team':'France' , 'P':1 , 'GD':-3 , 'GS':1 , 'GA':4},
{'team':'Uruguay' , 'P':7 , 'GD':4 , 'GS':4 , 'GA':0},
{'team':'SouthAfrica' , 'P':4 , 'GD':-2 , 'GS':3 , 'GA':5},
{'team':'Mexico' , 'P':4 , 'GD':1 , 'GS':3 , 'GA':2}]
print sorted(teamitems ,key = lambda x:(x['P'],x['GD'],x['GS'],x['GA']),reverse=True)
以上代碼實現了 按‘P',‘GD' ,‘GS' ,'GA' 四條件排序,reverse=True 表示降序
當然還可以
代碼如下:
from operator import itemgetter
print sorted(teamitems ,key = itemgetter('P','GD','GS','GA'),reverse=True)
新聞熱點
疑難解答