📜  Python sorted()函数与示例(1)

📅  最后修改于: 2023-12-03 14:46:04.175000             🧑  作者: Mango

Python sorted()函数与示例

sorted() 函数是 Python 内置的一个操作序列的函数。它可以对列表、元组、集合、字典等可迭代对象进行排序操作,该函数返回一个新的排好序的列表,而不会对原对象进行任何修改。

sorted() 函数的基本语法
sorted(iterable, key=None, reverse=False)

参数说明:

  • iterable:可迭代对象,可以是列表、元组、集合或字典等。
  • key:排序规则,指定一个Bkey函数来根据指定的元素进行排序,可以为 None。
  • reverse:排序规则,reverse=True 降序,reverse=False 升序(默认)。

返回值:排序后的列表。

sorted() 函数示例
对列表进行排序
>>> a = [3, 6, 1, 9, 8, 4]
>>> sorted(a)
[1, 3, 4, 6, 8, 9]

>>> b = ['hello', 'world', 'python', 'apple']
>>> sorted(b)
['apple', 'hello', 'python', 'world']
对元组进行排序
>>> a = (3, 6, 1, 9, 8, 4)
>>> sorted(a)
[1, 3, 4, 6, 8, 9]

>>> b = ('hello', 'world', 'python', 'apple')
>>> sorted(b)
['apple', 'hello', 'python', 'world']
对集合进行排序
>>> a = {3, 6, 1, 9, 8, 4}
>>> sorted(a)
[1, 3, 4, 6, 8, 9]

>>> b = {'hello', 'world', 'python', 'apple'}
>>> sorted(b)
['apple', 'hello', 'python', 'world']
对字典进行排序
>>> a = {'apple': 5, 'orange': 3, 'banana': 8, 'grape': 2}
>>> sorted(a)
['apple', 'banana', 'grape', 'orange']

>>> b = {'apple': 5, 'orange': 3, 'banana': 8, 'grape': 2}
>>> sorted(b, key=lambda x: b[x])
['grape', 'orange', 'apple', 'banana']

在对字典进行排序时,如果不指定排序规则,则默认按字典的键(Key)进行排序。如果要按字典的值(Value)进行排序,则需要借助 key 函数。

总结

sorted() 函数是 Python 中非常实用的一个排序函数。我们可以用它来对列表、元组、集合、字典等可迭代对象进行排序,而不会对原来的对象进行改变。在使用 sorted() 函数时,需要注意指定排序规则,以获得期望的排序结果。