当前位置:   article > 正文

python中的排序函数sorted与sort_python中sort和sorted

python中sort和sorted

1、list.sort方法与sorted函数区别

Python中有内置函数sorted(), list(列表)中也有函数list.sort()都可以进行排序。

list.sort():列表的排序方法会改变原来列表的的排序、只适用于列表排序、所以效率高

sorted():函数,适用于任意可迭代对象(字符串、元祖、列表、字典等),返回的是一个新列表

2、sorted函数 (list.sort方法用法类似)

sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list 

-- iterable可迭代类型,例如字典、列表、
-- cmp比较函数
-- key可迭代类型中某个属性,对给定元素的每一项进行排序
-- reverse降序或升序

--返回值:返回新的已排序的列表

2.1 基本用法 

  1. ls = [3, 6, 1, 8, 2, 7, 9]
  2. print(sorted(ls))
  3. # [1, 2, 3, 6, 7, 8, 9]

 2.2 key参数值的形式

(1)给key参数传入了一个lambda函数表达式,其person就代表列表里的每一个元素 

  1. ls = [('john', 178, 18), ('jane', 175, 23), ('dave', 180, 20),]
  2. print(sorted(ls, key=lambda person : person[2])) # sort by age
  3. # [('john', 178, 18), ('dave', 180, 20), ('jane', 175, 23)]
  1. dic = {"a":"2","b":"8","c":"6"}
  2. print(sorted(dic.items(),key=lambda x:x[0],reverse=True)) # 按key降序排序
  3. # [('c', '6'), ('b', '8'), ('a', '2')] # 返回的是列表
  1. dic = {"a":"2","b":"8","c":"6"}
  2. print(sorted(dic.items(),key=lambda x:x[1],reverse=True)) # 按value降序排序
  3. # [('b', '8'), ('c', '6'), ('a', '2')] # 返回的是列表

(2)给key参数传operator.itemgetter方法 

  1. import operator
  2. ls = [{"name":"Jack","age":18},{"name":"Lily","age":28}]
  3. ## 按照age排序
  4. print(sorted(ls, key=operator.itemgetter('age'), reverse=True))
  5. # [{'name': 'Lily', 'age': 28}, {'name': 'Jack', 'age': 18}]
  1. import operator
  2. ls = [
  3. {"name":"Jack","age":18, 'height':180},
  4. {"name":"Lily","age":28, 'height':175},
  5. {"name":"Jerry","age":28, 'height':173}
  6. ]
  7. ## 先按照age排序,若age相同,再比较height
  8. print(sorted(ls, key=operator.itemgetter('age','height')))
  9. """
  10. [
  11. {'name': 'Jack', 'age': 18, 'height': 180},
  12. {'name': 'Jerry', 'age': 28, 'height': 173},
  13. {'name': 'Lily', 'age': 28, 'height': 175}
  14. ]
  15. """
  1. import operator
  2. ## (name, scores, age)
  3. students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
  4. ## 先按照成绩排序,成绩相同再比较年龄
  5. print(sorted(students, key=operator.itemgetter(1,2)))
  6. # [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

3、几种常见的嵌套排序 

3.1 列表中嵌套字典,字典中key相同时,对字典value值排序

使用lambda表达式:

  1. dic = [{"name":"Jack","age":18},{"name":"Lily","age":28}]
  2. print(sorted(dic,key=lambda x:x['age'],reverse=True))
  3. # [{'name': 'Lily', 'age': 28}, {'name': 'Jack', 'age': 18}]

使用operator方式:

  1. import operator
  2. dic = [{"name":"Jack","age":18},{"name":"Lily","age":28}]
  3. print(sorted(dic, key=operator.itemgetter('age'),reverse=True))
  4. # [{'name': 'Lily', 'age': 28}, {'name': 'Jack', 'age': 18}]

3.2  字典嵌套字典的排序

思路是将字典转换为元组或列表

  1. dic = {1001:{"aa":1,"bb":2},1002:{"aa":2,"bb":0},1003:{"aa":0,"bb":3}}
  2. sorted_list = sorted(dic.items(),key=lambda x:x[1]['bb']) # x为(1001, {'aa': 1, 'bb': 2})的元组形式,按bb键排序
  3. print(sorted_list) # [(1002, {'aa': 2, 'bb': 0}), (1001, {'aa': 1, 'bb': 2}), (1003, {'aa': 0, 'bb': 3})]
  4. sorted_dic = {i[0]:i[1] for i in sorted_list}
  5. print(sorted_dic) # {1002: {'aa': 2, 'bb': 0}, 1001: {'aa': 1, 'bb': 2}, 1003: {'aa': 0, 'bb': 3}}
  6. ##########################################################################################
  7. ## 补充知识:
  8. print(list(dic.items()))
  9. # [(1001, {'aa': 1, 'bb': 2}), (1002, {'aa': 2, 'bb': 0}), (1003, {'aa': 0, 'bb': 3})]
  10. """
  11. dic.items()会将dic字典中的每项键值对key:value存储为一个元组(key,value),如下:
  12. dict_items([(1001, {'aa': 1, 'bb': 2}), (1002, {'aa': 2, 'bb': 0}), (1003, {'aa': 0, 'bb': 3})])
  13. list(dic.items())可以将其转换为列表,即[(1001, {'aa': 1, 'bb': 2}), (1002, {'aa': 2, 'bb': 0}), (1003, {'aa': 0, 'bb': 3})]
  14. """

核心是:sorted_list = sorted(dic.items(),key=lambda x:x[1]['bb']) # x为(1001, {'aa': 1, 'bb': 2})的元组形式,按bb键排序。

dic.items()会将dic字典中的每项键值对key:value存储为一个元组(key,value),如下: 
dict_items([(1001, {'aa': 1, 'bb': 2}), (1002, {'aa': 2, 'bb': 0}), (1003, {'aa': 0, 'bb': 3})])
list(dic.items())可以将其转换为列表,即[(1001, {'aa': 1, 'bb': 2}), (1002, {'aa': 2, 'bb': 0}), (1003, {'aa': 0, 'bb': 3})]

3.3 列表中嵌套字典,字典中key不同时,对字典value值排序

思路参考3.2,可以先转换为其他方便排序的类型,排完序再转回原来的形式。

可以将列表中的字典先放入到一个字典中,再对整个字典进行排序,在排序完成后,再转换成原来的列表套字典形式:

  1. import operator
  2. # 将成绩升序排序{name:scores}
  3. ls = [{"min":89},{"fei":90},{"hao":84},{"jhon":98}]
  4. dic = {key:value for x in ls for key,value in x.items()}
  5. print(dic) # {'min': 89, 'fei': 90, 'hao': 84, 'jhon': 98}
  6. sorted_list = sorted(dic.items(),key=operator.itemgetter(1))
  7. print(sorted_list) # [('hao', 84), ('min', 89), ('fei', 90), ('jhon', 98)]
  8. sorted_ls = [{i[0]:i[1]} for i in sorted_list]
  9. print(sorted_ls) # [{'hao': 84}, {'min': 89}, {'fei': 90}, {'jhon': 98}]

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/491297
推荐阅读
相关标签
  

闽ICP备14008679号