Python中sorted()函数
sorted()函数是Python中内置的排序函数,它可以对任何可迭代序列进行排序,包括字符串、元组、列表等。
sorted()函数的用法
# 对列表进行排序 list = [1, 3, 5, 7, 9, 2, 4, 6, 8] sorted_list = sorted(list) print(sorted_list) # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9] # 对元组进行排序 tuple = (1, 3, 5, 7, 9, 2, 4, 6, 8) sorted_tuple = sorted(tuple) print(sorted_tuple) # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9] # 对字符串进行排序 string = '123456789' sorted_string = sorted(string) print(sorted_string) # 输出:['1', '2', '3', '4', '5', '6', '7', '8', '9']
sorted()函数还可以接收一个key参数,用来指定根据哪个元素进行排序,比如:
# 根据字符串长度进行排序 list = ['Python', 'Java', 'C++', 'Go', 'Kotlin'] sorted_list = sorted(list, key=len) print(sorted_list) # 输出:['Go', 'Java', 'C++', 'Python', 'Kotlin'] # 根据字典中某个元素的值进行排序 dict = {'name': 'Alice', 'age': 20, 'height': 170} sorted_dict = sorted(dict, key=dict.get) print(sorted_dict) # 输出:['age', 'height', 'name']
sorted()函数还可以接收一个reverse参数,用来指定是否逆序排列,默认是False,即正序排列,如果指定为True,则为逆序排列。
# 正序排列 list = [1, 3, 5, 7, 9, 2, 4, 6, 8] sorted_list = sorted(list, reverse=False) print(sorted_list) # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9] # 逆序排列 list = [1, 3, 5, 7, 9, 2, 4, 6, 8] sorted_list = sorted(list, reverse=True) print(sorted_list) # 输出:[9, 8, 7, 6, 5, 4, 3, 2, 1]
:sorted()函数可以对任何可迭代序列进行排序,它还可以接收一个key参数,用来指定根据哪个元素进行排序,还可以接收一个reverse参数,用来指定是否逆序排列。