温馨提示×

python3的sorted函数怎么使用

小亿
72
2023-11-03 23:34:18
栏目: 编程语言

sorted()函数用于对列表、元组、字典等可迭代对象进行排序。

语法: sorted(iterable, key=None, reverse=False)

参数说明:

  • iterable:可迭代对象,如列表、元组、字典等。
  • key:用于指定排序的关键字,可根据自定义的函数来排序。
  • reverse:可选参数,用于指定是否按降序排序,默认为False(升序)。

示例:

  1. 对列表进行排序(默认为升序):

    numbers = [5, 2, 8, 1, 3]
    sorted_numbers = sorted(numbers)
    print(sorted_numbers)  # 输出:[1, 2, 3, 5, 8]
    
  2. 对列表进行降序排序:

    numbers = [5, 2, 8, 1, 3]
    sorted_numbers = sorted(numbers, reverse=True)
    print(sorted_numbers)  # 输出:[8, 5, 3, 2, 1]
    
  3. 对字典按值进行排序:

    student_scores = {'Alice': 85, 'Bob': 70, 'Charlie': 92, 'David': 65}
    sorted_scores = sorted(student_scores.items(), key=lambda x: x[1], reverse=True)
    print(sorted_scores)  # 输出:[('Charlie', 92), ('Alice', 85), ('Bob', 70), ('David', 65)]
    

    在这个例子中,我们使用了lambda函数作为key参数,指定了按字典值进行排序(即第一个元素的索引1),并且按降序排列。

注意:sorted()函数返回的是一个新的排序后的列表,原始列表不会被修改。

0