Python 基于字典里的指定key进行排序
对下面列表基于age进行排序
items = [{‘age‘: 28, ‘name‘: ‘Tom‘}, {‘age‘: 25, ‘name‘: ‘Jack‘}, {‘age‘: 18, ‘name‘: ‘Alex‘}]
items = [{‘age‘: 28, ‘name‘: ‘Tom‘}, {‘age‘: 25, ‘name‘: ‘Jack‘}, {‘age‘: 18, ‘name‘: ‘Alex‘}]
方法一:
sorted(items,key=lambda item: item[‘age‘])
方法二:
from operator import itemgetter
sorted(items,key=itemgetter(‘age‘))
备注:以上两个方法同样适用于 max()、min() 函数。默认为升序,如果需要倒序,需要指定 reverse=True 参数。
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
世事一场大梦 2020-11-17
xiaoseyihe 2020-11-16
Morelia 2020-11-03
CloudXli 2020-11-03
文山羊 2020-10-31
comtop0 2020-10-31
pythonxuexi 2020-10-30
三石 2020-10-29
chaochao 2020-10-27
PythonMaker 2020-10-27