python字典排序 python字典多条件排序

1850阅读 0评论2014-06-30 ewayfly
分类:Python/Ruby

字典多条件排序方法实例,分别使用lambda和itemgetter实现。

项目编写过程中,总能遇见对字典进行排序什么的,如果要实现多条件排序只需要下面几行代码实现。
充分体现了python的好处了。

  1. teamitems = [{'team':'France' , 'P':1 , 'GD':-3 , 'GS':1 , 'GA':4},
  2.             {'team':'Uruguay' , 'P':7 , 'GD':4 , 'GS':4 , 'GA':0},
  3.             {'team':'SouthAfrica' , 'P':4 , 'GD':-2 , 'GS':3 , 'GA':5},
  4.             {'team':'Mexico' , 'P':4 , 'GD':1 , 'GS':3 , 'GA':2}]
  5. print sorted(teamitems ,key = lambda x:(x['P'],x['GD'],x['GS'],x['GA']),reverse=True)
以上代码()实现了 按‘P',‘GD' ,‘GS' ,'GA' 四条件排序,reverse=True 表示降序
当然还可以

  1. from operator import itemgetter
  2. print sorted(teamitems ,key = itemgetter('P','GD','GS','GA'),reverse=True)
上一篇:PHP函数重载小例子
下一篇:PHP生成二维码多种方法实例教程