您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

python如何通过列表中字典的值对列表进行排序

2024/4/16 13:18:52发布32次查看
一. 按字典值排序(默认为升序)
x = {1:2, 3:4, 4:3, 2:1, 0:0}  
1. sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))  print sorted_x  
输出结果:[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]  
如果要降序排序,可以指定reverse=true
2. sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=true)  print sorted_x  
输出结果:[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
二. 或者直接使用list的reverse方法将sorted_x顺序反转  
sorted_x.reverse()  
三. 更为常用的方法是,用lambda表达式  
sorted_x = sorted(x.iteritems(), key=lambda x : x[1])  print sorted_x  
输出结果:[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]  
orted_x = sorted(x.iteritems(), key=lambda x : x[1], reverse=true)  print sorted_x  
输出结果:[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
以上就是python如何通过列表中字典的值对列表进行排序的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product