Python 的 sorted() 函数用于对可迭代对象进行排序。它的基本语法如下:

sorted(iterable, key=None, reverse=False)

其中,iterable 是要排序的可迭代对象,可以是列表、元组、字符串等;key 是一个可选参数,用于指定一个函数,该函数将被用于每个元素来提取排序依据;reverse 是一个可选参数,用于指定是否降序排序,默认为 False,即升序排序。

下面是一些示例用法:

  1. 对列表进行排序:
numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # [1, 2, 5, 8, 9]
  1. 对字符串进行排序:
string = 'hello'
sorted_string = sorted(string)
print(sorted_string)  # ['e', 'h', 'l', 'l', 'o']
  1. 使用 key 参数指定排序依据:
students = [('Alice', 18), ('Bob', 20), ('Charlie', 15)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)  # [('Charlie', 15), ('Alice', 18), ('Bob', 20)]
  1. 使用 reverse 参数进行降序排序:
numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)  # [9, 8, 5, 2, 1]

需要注意的是,sorted() 函数返回一个新的已排序的列表,原始列表不会被修改。如果想要在原地进行排序,可以使用列表的 sort() 方法。

Python sorted() 函数详解:排序可迭代对象

原文地址: https://www.cveoy.top/t/topic/dRsw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录