欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python字典多條件排序方法實例

 更新時間:2014年06月30日 11:26:45   投稿:junjie  
這篇文章主要介紹了python字典多條件排序方法實例,分別使用lambda和itemgetter實現(xiàn),需要的朋友可以參考下

項目編寫過程中,總能遇見對字典進行排序什么的,如果要實現(xiàn)多條件排序只需要下面幾行代碼實現(xiàn)。充分體現(xiàn)了python的好處了。

復(fù)制代碼 代碼如下:

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)


以上代碼實現(xiàn)了 按‘P',‘GD' ,‘GS' ,'GA' 四條件排序,reverse=True 表示降序

當(dāng)然還可以

復(fù)制代碼 代碼如下:

from operator import itemgetter
print sorted(teamitems ,key = itemgetter('P','GD','GS','GA'),reverse=True)

相關(guān)文章

最新評論