Home > Backend Development > Python Tutorial > python字典多条件排序方法实例

python字典多条件排序方法实例

WBOY
Release: 2016-06-16 08:43:33
Original
1285 people have browsed it

项目编写过程中,总能遇见对字典进行排序什么的,如果要实现多条件排序只需要下面几行代码实现。充分体现了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)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template