Python sorted() 函数从可迭代对象中的项目返回一个新的排序列表。排序顺序可以设置为升序或降序。但是,字符串按字母顺序排序,数字按数字顺序排序。
sorted() 是用于对可迭代对象进行排序的常用内置函数之一。可迭代对象是一个对象,它使我们能够通过迭代它们来一次访问一个项目,例如列表、元组、字符串等。
语法
Python sorted() 函数的语法如下所示 -
sorted(iterObject, key, reverse)
参数
Python sorted() 函数接受三个参数,所有这些参数都是可选的 -
- iterObject − 它表示一个对象,例如列表、字符串或元组。
- key − 它指定一个表示比较键的函数。
- reverse − 此参数指定排序顺序。如果其值设置为 True,则顺序将为降序和升序(如果设置为 False)。默认值为 False。
返回值
Python sorted() 函数返回一个排序列表。
sorted() 函数示例
练习以下示例来理解 Python 中 sorted() 函数的使用:
示例:使用 sorted() 函数
包含字符串的列表将按字母顺序排序。以下示例显示了 Python sorted() 函数的用法,其中我们创建了一个列表并尝试对其进行排序。
orgnlStrList = ["Simply", "Easy", "Learning", "QikepuCOM", "Point"]
print("Before Sorting:", orgnlStrList)
print("Printing the list items after sorting:")
print(sorted(orgnlStrList))
当我们运行上述程序时,它会产生以下结果——
Before Sorting: ['Simply', 'Easy', 'Learning', 'QikepuCOM', 'Point']
Printing the list items after sorting:
['Easy', 'Learning', 'Point', 'Simply', 'QikepuCOM']
Printing the list items after sorting:
['Easy', 'Learning', 'Point', 'Simply', 'QikepuCOM']
示例:使用 sorted() 对数字列表进行排序
在此示例中,我们将按升序对数字列表进行排序。
numericList = [88, 89, 81, 82, 86, 85, 83]
print("Before Sorting:", numericList)
print("Printing the list items after sorting:")
print(sorted(numericList))
以下是上述代码的输出 -
Before Sorting: [88, 89, 81, 82, 86, 85, 83]
Printing the list items after sorting:
[81, 82, 83, 85, 86, 88, 89]
Printing the list items after sorting:
[81, 82, 83, 85, 86, 88, 89]
示例:带有 'key' 参数的 sorted() 函数
当我们将 “key” 参数的值指定为 “len” 时,将在对列表进行排序时比较字符串的长度,而不是字符串本身。下面的代码演示了如何根据项目的长度对列表进行排序。
orgnlStrList = ["Simply", "Easy", "Learning", "qikepucom", "Point"]
print("Before Sorting:", orgnlStrList)
print("sorting the list items by length:")
print(sorted(orgnlStrList, key=len))
上述代码的输出如下 -
Before Sorting: ['Simply', 'Easy', 'Learning', 'qikepucom', 'Point']
sorting the list items by length:
['Easy', 'Point', 'Simply', 'Learning', 'qikepucom']
sorting the list items by length:
['Easy', 'Point', 'Simply', 'Learning', 'qikepucom']
示例:带有 'reverse' 参数的 sorted() 函数
如前所述,如果 “reverse” 参数的值设置为 “True”,则排序顺序将按降序排列。在下面的代码中,将创建一个数字列表。然后我们按降序打印其项。
numericList = [12, 24, 36, 48, 60, 72, 84]
print("Before Sorting:", numericList)
print("sorting the list items in descending order:")
print(sorted(numericList, reverse=True))
以下是上述代码的输出 -
Before Sorting: [12, 24, 36, 48, 60, 72, 84]
sorting the list items in descending order:
[84, 72, 60, 48, 36, 24, 12]
sorting the list items in descending order:
[84, 72, 60, 48, 36, 24, 12]