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

yipeiwu_com5年前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)

相关文章

python3 写一个WAV音频文件播放器的代码

环境:ubuntu 16.04 python3.5 pycharm 包 : wave pyaudio sys 上代码:AudioPlayer.py # coding:utf-8 #...

Python线程详解

Python线程详解

1. 线程基础 1.1. 线程状态 线程有5种状态,状态转换的过程如下图所示: 1.2. 线程同步(锁) 多线程的优势在于可以同时运行多个任务(至少感觉起来是这样)。但是当线程需要共享...

Pytorch中index_select() 函数的实现理解

函数形式: index_select( dim, index ) 参数: dim:表示从第几维挑选数据,类型为int值; index:表示从第一个参数维度中的哪个...

Python内置函数 next的具体使用方法

Python 3中的File对象不支持next()方法。 Python 3有一个内置函数next(),它通过调用其next ()方法从迭代器中检索下一个项目。 如果给定了默认值,则在迭代...

用Python写一个模拟qq聊天小程序的代码实例

Python 超简单的聊天程序 客户端: import socket, sys host = '10.248.27.23' # host = raw_input("Plz imput...