python231116-如何在 Python 中排序列表?

在 Python 中,可以使用以下方法对列表进行排序:

* `sort()` 方法
* `sorted()` 函数

`sort()` 方法是内置方法,可以直接在列表上调用。 `sorted()` 函数是内置函数,可以对任何可迭代对象进行排序。

以下是使用 `sort()` 方法对列表进行排序的示例:

my_list = ['a', 'b', 'c']
my_list.sort()
print(my_list) 
# 输出:['a', 'b', 'c']

以下是使用 `sorted()` 函数对列表进行排序的示例:

my_list = ['a', 'b', 'c']
sorted_list = sorted(my_list)
print(sorted_list) 
# 输出:['a', 'b', 'c']

除了以上方法,还可以使用 `reverse()` 方法对列表进行反向排序。

以下是使用 `reverse()` 方法对列表进行反向排序的示例:

my_list = ['a', 'b', 'c']
sorted_list = sorted(my_list)
print(sorted_list) 
# 输出:['a', 'b', 'c']

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注