欢迎访问宙启技术站
智能推送

Python中的sorted()函数:排序序列并返回新列表

发布时间:2023-07-04 20:27:10

Python中的sorted()函数是用来排序序列并返回一个新的列表。

sorted()函数可以对列表、元组、字符串或字典进行排序。它接受一个可迭代对象作为参数,并返回一个新的已排序的列表。

在对列表进行排序时,sorted()函数会返回一个新的列表,而不会修改原始列表。例如:

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
print(numbers)  # 输出:[3, 1, 4, 1, 5, 9, 2, 6, 5, 3]

在对元组进行排序时,sorted()函数同样会返回一个新的已排序的列表。例如:

letters = ('d', 'c', 'a', 'b')
sorted_letters = sorted(letters)
print(sorted_letters)  # 输出:['a', 'b', 'c', 'd']
print(letters)  # 输出:('d', 'c', 'a', 'b')

在对字符串进行排序时,sorted()函数会将字符串的每个字符按照字母顺序排序,并返回一个新的字符串。例如:

word = 'python'
sorted_word = sorted(word)
print(sorted_word)  # 输出:['h', 'n', 'o', 'p', 't', 'y']
print(word)  # 输出:'python'

当对字典进行排序时,sorted()函数默认会根据字典的键进行排序,并返回一个已排序的键的列表。例如:

scores = {'Alice': 85, 'Bob': 75, 'Charlie': 90, 'David': 80}
sorted_scores = sorted(scores)
print(sorted_scores)  # 输出:['Alice', 'Bob', 'Charlie', 'David']
print(scores)  # 输出:{'Alice': 85, 'Bob': 75, 'Charlie': 90, 'David': 80}

如果想根据字典的值进行排序,可以使用sorted()函数的key参数来指定排序的依据。例如:

sorted_scores = sorted(scores, key=lambda x: scores[x])
print(sorted_scores)  # 输出:['Bob', 'David', 'Alice', 'Charlie']

除了默认的升序排序外,sorted()函数还接受一个可选的reverse参数,用于控制排序的顺序。如果reverse参数的值为True,则会进行降序排序。例如:

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)  # 输出:[9, 6, 5, 5, 4, 3, 3, 2, 1, 1]

总结起来,Python中的sorted()函数是一个非常有用的函数,它可以对序列进行排序并返回一个新的已排序的列表。无论是对列表、元组、字符串还是字典,sorted()函数都能很方便地实现排序操作,并且可以根据需要指定排序的规则和顺序。