如何在 Python 中对列表中的对象进行排序?
在 Python 中,列表是一个有序序列,可以保存多种对象类型,例如整数、字符或浮点数。在其他编程语言中,列表相当于数组。方括号用于表示它,逗号 (,) 用于分隔列表中的两个项目。
在本文中,我们将向您展示如何使用 Python 对列表中的对象和元素进行排序。以下是完成此任务的不同方法 -
使用 sort() 方法
使用 sorted() 方法
假设我们获取了一个包含一些元素的列表。我们将按升序或降序排序后返回列表元素。
注意 - 如果列表的对象/元素是字符串,则元素按字母顺序排序。
方法 1:使用 sort() 方法
sort() 方法对原始列表进行就地排序。它表示 sort() 方法会更改列表元素的顺序
默认情况下,sort() 方法使用小于运算符 (<) 对列表的条目进行排序,即按升序排序。换句话说,它优先考虑较小的元素,而不是较大的元素。
要按从高到低(降序)对元素进行排序,请在 sort() 方法中使用 reverse=True 参数。
list.sort(reverse=True)
示例 1
以下程序使用 sort() 方法按升序和降序对列表元素进行排序 −
# input list lst = [10, 4, 12, 1, 9, 5] # sorting elements of the list in ascending order lst.sort() print("Sorting list items in ascending order: ", lst) # sorting elements of the list in descending order lst.sort(reverse=True) print("Sorting list items in descending order: ", lst)
输出
执行时,上述程序将生成以下输出 -
Sorting list items in ascending order: [1, 4, 5, 9, 10, 12] Sorting list items in descending order: [12, 10, 9, 5, 4, 1]
在本例中,我们给出了一个随机值列表。然后将 sort() 方法应用于列表,该方法按升序对给定列表进行排序,并按升序打印列表。然后通过将附加键传递给 sort() 函数 reverse=True,按降序对同一列表进行排序,并按降序打印列表。
示例:2 对于包含字符串值的列表
以下程序使用 sort() 方法按升序和降序对列表元素(字符串)进行排序 −
# input list lst = ['hello','this','is','tutorials','point','website','welcome','all'] # sorting string elements of the list in ascending order lst.sort() print("Sorting list items in ascending order: ", lst) # sorting string elements of the list in descending order lst.sort(reverse=True) print("Sorting list items in descending order: ", lst)
输出
执行时,上述程序将生成以下输出 -
Sorting list items in ascending order: ['all', 'hello', 'is', 'point', 'this', 'tutorials', 'website', 'welcome'] Sorting list items in descending order: ['welcome', 'website', 'tutorials', 'this', 'point', 'is', 'hello', 'all']
我们可以看到所有元素都按字母顺序排序
方法 2:使用 sorted() 方法
sorted() 函数返回给定可迭代对象的排序列表。
您可以选择升序或降序。数字按数字顺序排序,而字符串按字母顺序排列。
语法
sorted(iterable, key=key, reverse=reverse)
参数
iterable − 它是一个序列
key − 将执行以确定顺序的函数。默认值为 None。
reverse − 布尔表达式。True 表示升序排序,False 表示降序排序。默认值为 False。
示例
以下程序使用 sorted() 方法按升序和降序对列表元素进行排序 −
# input list lst = [10, 4, 12, 1, 9, 5] # sorting elements of the list in ascending order print("Sorting list items in ascending order: ", sorted(lst)) # sorting elements of the list in descending order print("Sorting list items in descending order: ", sorted(lst, reverse=True))
输出
执行时,上述程序将生成以下输出 -
Sorting list items in ascending order: [1, 4, 5, 9, 10, 12] Sorting list items in descending order: [12, 10, 9, 5, 4, 1]
在此示例中,我们提供了一组随机数。我们将列表作为参数提供给 sorted() 方法,该方法按升序对给定列表进行排序并打印。然后通过为 sorted() 方法提供一个附加键 reverse=True,按降序对同一列表进行排序,并按降序打印列表。
结论
在本文中,我们学习了如何使用函数 sort() 和 sorted () 对列表对象/元素进行排序。我们还学习了如何使用相同的函数按降序对项目列表进行排序。我们还讨论了如果列表包含字符串作为对象,将如何对列表进行排序。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

