python-内建函数-排序函数sorted函数

1. 排序函数

  • sorted()函数: 对所有可迭代的对象进行排序操作

  • 语法格式:

    sorted(iterable,*,key=None,reverse=False)
    
    • key: 指定带有单个参数的函数,用于从interable的每个元素取出比较的键,默认为None(直接比较元素)
    • reverse: 排序规则,True降序,False升序(默认)
  • 示例:

    • 示例1、对列表排序

      n = [2, 3, 4, 1, 5]
      s = ["b","c","a"]
      print(sorted(n))
      print(sorted(s))
      
    • 示例2、对字典中的值排序

      dict = {'a':86, 'b':23, 'c':45}
      result = sorted(dict.items(), key=lambda x:x[1])
      print(result)
      

2. 排序函数案例

  • 排序函数案例

    #!/usr/bin/env python3
    # _*_ coding: utf-8 _*_
    # Author:shichao
    # File: .py
    
    
    # 对列表排序
    n = [3,1,2,6,8]
    s = ["b","d","a","c"]
    
    print(sorted(n))
    print(sorted(s))
    
    
    # 对字典排序
    dict = {'a':86, 'b':23, 'c':45}
    result = sorted(dict.items(), key=lambda x:x[1])
    print(result)
    
    
    
posted @ 2023-01-06 10:06  七月流星雨  阅读(33)  评论(0编辑  收藏  举报