本文实例讲述了Python常见排序操作。分享给大家供大家参考,具体如下:
字典排序
- 按value排序
1
2
3
|
d1 = { "name" : "python" , "bank" : "icbc" , "country" :china} # reverse是否倒序,x[1]代表value,x[0]为key d1 = sorted (d1.items(), lambda x: x[ 1 ],reverse = True ) |
- 按key排序
1
2
|
d1 = { "name" : "python" , "bank" : "icbc" , "country" :china} d1 = sorted (d1.items()) |
列表排序
- 不去重排序
1
2
3
|
l = [ 3 , 2 , 4 , 5 ] l = sorted (l) # 升序 # l = sorted(l,reverse=True) # 降序 |
- 去重排序
1
2
3
4
|
l = [ 3 , 2 , 3 , 5 , 1 ] l = set (l) # 使用set集合去重 l = list (l) # l = sorted (l) # 排序 |
字典列表排序
1
2
3
4
5
6
7
|
# 以age升序排序 L = [ { "name" : "python" , "age" : 12 }, { "name" : "ghj" , "age" : 10 }, { "name" : "java" , "age" : 17 } ] L = sorted (L,key = lambda x: x[ "age" ]) |
根据指定列表的元素顺序进行排序
用途:对于取出MySQL与MongoDB的数据时,我们常常需要对数据进行位置更换顺序,此时此种排序就能很好的解决我们的问题,对于下面列子中的sortList的数据我们可以使用Redis进行存储
1
2
3
4
5
6
7
8
|
# 指定列表,假设存储的是curList中的ID列表 sortList = [ "4" , "3" , "5" , "2" , "1" ] # 当前列表 curList = [{ "id" : "1" , "province" : "河南" },{ "id" : "2" , "province" : "河北" },{ "id" : "3" , "湖南" },{ "id" : "4" , "province" : "湖北" },{ "id" : "5" , "province" : "江西" }] # 根据指定列表中的ID顺序,对当前列表进行排序 curList = sorted (curList,key = lambda item:sortList.index(item[ "id" ])) print (curList) # [{"id":"4","province":"湖北"},{"id":"3","province":"湖南"},{"id":"5","province":"江西"},{"id":"2","province":"河北"},{"id":"1","province":"河南"}] |
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/y472360651/article/details/78132213