本文实例讲述了Python常见排序操作。分享给大家供大家参考,具体如下:
字典排序
d1 = {"name":"python","bank":"icbc","country":china}# reverse是否倒序,x[1]代表value,x[0]为keyd1 = sorted(d1.items(),lambda x: x[1],reverse=True)
d1 = {"name":"python","bank":"icbc","country":china}d1 = sorted(d1.items())
列表排序
l = [3,2,4,5]l = sorted(l) # 升序# l = sorted(l,reverse=True) # 降序
l = [3,2,3,5,1]l = set(l) # 使用set集合去重l = list(l) #l = sorted(l) # 排序
字典列表排序
# 以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进行存储
# 指定列表,假设存储的是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程序设计有所帮助。
注:相关教程知识阅读请移步到python教程频道。