python sorted的使用方法
Python的sorted函数用于对可迭代对象进行排序。它的基本语法如下:
sorted(iterable, key=None, reverse=False)
其中,iterable是要排序的可迭代对象,可以是列表、元组、字符串等;key是一个可选参数,用于指定一个函数,该函数将被用于每个元素来提取排序依据;reverse是一个可选参数,用于指定是否降序排序,默认为False,即升序排序。
下面是一些示例用法:
- 对列表进行排序:
numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [1, 2, 5, 8, 9]
- 对字符串进行排序:
string = "hello"
sorted_string = sorted(string)
print(sorted_string) # ['e', 'h', 'l', 'l', 'o']
- 使用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)]
- 使用reverse参数进行降序排序:
numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # [9, 8, 5, 2, 1]
需要注意的是,sorted函数返回一个新的已排序的列表,原始列表不会被修改。如果想要在原地进行排序,可以使用列表的sort方法。
原文地址: http://www.cveoy.top/t/topic/iXEN 著作权归作者所有。请勿转载和采集!