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

yipeiwu_com6年前Python基础

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

相关文章

Python入门_浅谈for循环、while循环

Python入门_浅谈for循环、while循环

Python中有两种循环,分别为:for循环和while循环。 1. for循环 for循环可以用来遍历某一对象(遍历:通俗点说,就是把这个循环中的第一个元素到最后一个元素依次访问一次)...

提升Python效率之使用循环机制代替递归函数

斐波那契数列 当年,典型的递归题目,斐波那契数列还记得吗? def fib(n): if n==1 or n==2: return 1 else: retur...

在Pytorch中计算卷积方法的区别详解(conv2d的区别)

在二维矩阵间的运算: class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=...

tensorflow之获取tensor的shape作为max_pool的ksize实例

实验发现,tensorflow的tensor张量的shape不支持直接作为tf.max_pool的参数,比如下面这种情况(一个错误的示范): self.max_pooling1 =...

python pytest进阶之fixture详解

前言 学pytest就不得不说fixture,fixture是pytest的精髓所在,就像unittest中的setup和teardown一样,如果不学fixture那么使用pytes...