WordPress网站建设宣传图片

Python字典按照值(value)的大小进行排序方法

释放双眼,带上耳机,听听看~!

Python字典按照值(value)的大小进行排序可以使用collections的Counter()函数和sorted函数两种方式进行,关于Counter和sorted函数之前也记录过,关于这两个详细的就不说了,有需要可以自己看看:

python Counter()函数介绍 – 统计值出现的次数

Python3 sorted() 函数 – 对所有可迭代的对象进行排序操作。

下面我们直接看使用它们对Python字典按照值(value)的大小进行排序的示例代码:

sorted函数实现

test_dict = {'xm': 99, 'xh': 100, 'xw': 80}

# sorted() 函数可以对列表[]进行从小到大排序,对于字典{}dict,sorted函数默认只按照dict的key进行排序,如果是对字典的value进行排序的话,要对dict进行调整变形才可。
# 利用zip函数把dict转换成一个列表,列表中每个元素都是一个tuple,tuple大小比较原理是,先比较第一个元素,第一个相同在比较第二个。
z = zip(test_dict.values(), test_dict.keys())

# sorted函数默认为升序,设置参数reverse = True 降序
print(sorted(z, reverse=True)) 

输出结果

[(100, 'xh'), (99, 'xm'), (80, 'xw')]

至于上面的列表怎么转字典,就很简单了,我就不重复啰嗦了,如果不会就该去补补基础了。

sorted函数可以进行指定元素排序。

array = [{"age":20,"name":"a"},{"age":25,"name":"b"},{"age":10,"name":"c"}]
array = sorted(array,key=lambda x:x["age"])
print(array)

输出结果

[{'age': 10, 'name': 'c'}, {'age': 20, 'name': 'a'}, {'age': 25, 'name': 'b'}]

Counter()函数实现

Counter()函数返回值可以理解为一个字典,所以对传回来的统计结果的操作都可以当作对字典的操作(Counter类继承dict类,所以它能使用dict类里面的方法)

from collections import Counter

test_dict = {'xm': 99, 'xh': 100, 'xw': 80}
new_dict = Counter(test_dict)
print(new_dict)

输出结果

Counter({'xh': 100, 'xm': 99, 'xw': 80})

使用Counter(dict).most_common()则返回一个列表,列表中的元素由元组组成(字典的key,value),按照字典value从大到小排序。

from collections import Counter

test_dict = {'xm': 99, 'xh': 100, 'xw': 80}
# new_dict = Counter(test_dict)
# print(new_dict)

new_dict = Counter(test_dict).most_common()
print(new_dict)

输出结果

[('xh', 100), ('xm', 99), ('xw', 80)]

给TA打赏
共{{data.count}}人
人已打赏
Python RequestsPython爬虫Python笔记

Python requests获取状态码

2023-4-22 19:53:46

Python字典Python笔记

Python获取字典的前x个元素

2023-5-10 20:38:32

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索
展开目录