Python 如何对列表中的对象进行排序

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()函数对列表对象/元素进行排序。我们还学习了如何使用同样的函数对一组项目进行降序排序。我们还讨论了如果列表包含字符串对象,它将如何进行排序。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程