解释Python中的sorted()函数
发布时间:2023-09-24 02:39:12
Python中的sorted()函数用于对可迭代对象进行排序操作,并返回一个新的已排序的列表。sorted()函数具有以下特点:
1. sorted()函数可以对字符串、列表、元组、字典和集合等可迭代对象进行排序。对于字符串,会按照字符的顺序进行排序;对于列表、元组和集合等可迭代对象,会按照元素的顺序进行排序;对于字典,默认情况下会按照字典的键进行排序。
2. sorted()函数的 个参数是要排序的可迭代对象,第二个参数是排序的规则。排序规则可以通过key参数进行指定,key参数是一个函数,用于从可迭代对象的每个元素中提取用于排序的键。例如,可以使用lambda函数指定按字典值进行排序。
3. sorted()函数的返回值是一个新的已排序的列表。原始的可迭代对象保持不变。如果想在原地排序可迭代对象,可以使用列表的sort()方法进行操作。
下面是sorted()函数的用法示例:
# 对列表进行排序
nums = [3, 1, 4, 2, 5]
sorted_nums = sorted(nums) # 返回一个已排序的新列表
print(sorted_nums) # 输出: [1, 2, 3, 4, 5]
print(nums) # 输出: [3, 1, 4, 2, 5]
# 对字符串进行排序
string = "python"
sorted_string = sorted(string) # 返回一个已排序的新列表
print(sorted_string) # 输出: ['h', 'n', 'o', 'p', 't', 'y']
print(string) # 输出: python
# 对字典按键进行排序
scores = {"Alice": 90, "Bob": 80, "Cathy": 95}
sorted_scores = sorted(scores) # 返回一个已排序的新列表
print(sorted_scores) # 输出: ['Alice', 'Bob', 'Cathy']
print(scores) # 输出: {'Alice': 90, 'Bob': 80, 'Cathy': 95}
# 使用key参数指定排序规则
scores = {"Alice": 90, "Bob": 80, "Cathy": 95}
sorted_scores = sorted(scores, key=lambda x: scores[x]) # 按值进行排序
print(sorted_scores) # 输出: ['Bob', 'Alice', 'Cathy']
综上所述,sorted()函数是Python中用于对可迭代对象进行排序的函数,通过指定排序规则来返回一个新的已排序的列表。可以应用于各种可迭代对象,并具有灵活的用法。
