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

Python中的sorted函数:用法与例子

发布时间:2023-07-01 18:34:31

在Python中,sorted()函数是一种用于对可迭代对象进行排序的内置函数。它可以对各种数据类型进行排序,包括列表、元组、字典和字符串等。

sorted()函数的一般形式如下:

sorted(iterable, key=..., reverse=...)

其中,iterable表示要排序的可迭代对象,key是一个可选的函数,用于指定排序的依据,reverse表示排序顺序是否为降序,默认为False(升序)。

下面我们来看一些使用sorted()函数的常见用法和示例。

1. 对列表进行排序:

列表是Python中最常见的数据类型之一,sorted()函数可以对列表中的元素进行排序。

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

2. 对元组进行排序:

元组是不可变的序列类型,同样可以使用sorted()函数进行排序。

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

3. 对字典进行排序:

字典是一种键值对集合,使用sorted()函数可以根据键或值对字典进行排序。

scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Dave': 95}
sorted_scores = sorted(scores)  # 根据键进行排序
print(sorted_scores)  # 输出 ['Alice', 'Bob', 'Charlie', 'Dave']

sorted_scores = sorted(scores, key=scores.get)  # 根据值进行排序
print(sorted_scores)  # 输出 ['Charlie', 'Alice', 'Bob', 'Dave']

4. 对字符串进行排序:

字符串是一种序列类型,在使用sorted()函数时,它会将字符串的每个字符作为一个单独的元素进行排序。

string = "python"
sorted_string = sorted(string)
print(sorted_string)  # 输出 ['h', 'n', 'o', 'p', 't', 'y']

5. 使用key参数进行自定义排序:

通过将一个自定义的函数传递给key参数,我们可以根据特定的规则进行排序。这个函数将会被应用于每个元素上,并且返回一个用于排序的值。

fruits = ['apple', 'banana', 'orange', 'cherry']
sorted_fruits = sorted(fruits, key=len)
print(sorted_fruits)  # 输出 ['apple', 'banana', 'cherry', 'orange']

在上述代码中,key=len是一个匿名函数,它根据元素的长度来进行排序。

6. 指定排序顺序为降序:

通过设置reverse参数为True,我们可以将排序顺序改为降序。

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

以上就是sorted()函数的用法和示例。通过使用sorted()函数,我们可以方便地对各种数据类型进行排序,并且可以根据需要进行自定义排序。