gpt4 book ai didi

python 使用值来排序一个字典的方法

转载 作者:qq735679552 更新时间:2022-09-27 22:32:09 25 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章python 使用值来排序一个字典的方法由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

下面先看下python 使用值排序字典的方法 。

?
1
2
3
4
5
6
7
In [ 8 ]: a = { 'x' : 11 , 'y' : 22 , 'c' : 4 }
In [ 9 ]: import operator
In [ 10 ]: sorted (a.items(),key = operator.itemgetter( 1 ))
Out[ 10 ]: [( 'c' , 4 ), ( 'x' , 11 ), ( 'y' , 22 )]
In [ 11 ]: a = { 'x' : 11 , 'y' : 22 , 'c' : 4 }
In [ 12 ]: sorted (a.items(),key = lambda x:x[ 1 ])
Out[ 12 ]: [( 'c' , 4 ), ( 'x' , 11 ), ( 'y' , 22 )]

sort 方法会就地排序列表,不会把原列表复制一份 。

sorted 会新建一个列表作为返回值,接受任何形式的可迭代对象作为参数 。

sorted 和 sort的可选参数

  reverse  默认为False,如果设置为True则降序排列 。

      key 这个是一个只有一个参数的函数,会应用到序列中的每一个元素上,如果key=len,就会按照字符串的长度排序 。

补充:下面看下Python字典按值排序的方法 。

法1: (默认升序排序,加  reverse = True 指定为降序排序) 。

?
1
2
# sorted的结果是一个list
   dic1SortList = sorted ( dic1.items(),key = lambda x:x[ 1 ],reverse = True )

法2:

?
1
2
import operator
sorted_x = sorted (d.items(),key = operator.itemgetter( 1 ))

法3:包含字典dict的列表list的排序方法与dict的排序类似,如下:  。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
x = [{ 'name' : 'Homer' , 'age' : 39 }, { 'name' : 'Bart' , 'age' : 10 }]
sorted_x = sorted (x, key = operator.itemgetter( 'name' ))
print sorted_x
#[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]
sorted_x = sorted (x, key = operator.itemgetter( 'name' ), reverse = True )
print sorted_x
#[{'age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'Bart'}]
sorted_x = sorted (x, key = lambda x : x[ 'name' ])
print sorted_x
#[{'age': 10, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]
sorted_x = sorted (x, key = lambda x : x[ 'name' ], reverse = True )
print sorted_x
#[{'age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'Bart'}]

总结 。

以上所述是小编给大家介绍的python 使用值来排序一个字典的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我网站的支持! 。

原文链接:http://www.cnblogs.com/shenxiaolin/p/9368544.html 。

最后此篇关于python 使用值来排序一个字典的方法的文章就讲到这里了,如果你想了解更多关于python 使用值来排序一个字典的方法的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com