当前位置:Gxlcms > Python > python字典多条件排序方法实例

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

时间:2021-07-01 10:21:17 帮助过:5人阅读

项目编写过程中,总能遇见对字典进行排序什么的,如果要实现多条件排序只需要下面几行代码实现。充分体现了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)

人气教程排行