温馨提示×

python中的sort排序函数怎么使用

小亿
83
2024-04-20 17:49:43
栏目: 编程语言

在Python中,可以使用sort()方法来对列表进行排序。sort()方法可以用于对列表中的元素进行升序排序或者降序排序。示例如下:

  1. 对列表进行升序排序:
my_list = [4, 2, 7, 1, 3]
my_list.sort()
print(my_list)  # 输出:[1, 2, 3, 4, 7]
  1. 对列表进行降序排序:
my_list = [4, 2, 7, 1, 3]
my_list.sort(reverse=True)
print(my_list)  # 输出:[7, 4, 3, 2, 1]

另外,Python还提供了内置函数sorted()来对任何可迭代对象进行排序,sorted()函数会返回一个新的已排序的列表,而不改变原来的列表。示例如下:

my_list = [4, 2, 7, 1, 3]
sorted_list = sorted(my_list)
print(sorted_list)  # 输出:[1, 2, 3, 4, 7]

# 对字符串进行排序
my_string = "python"
sorted_string = sorted(my_string)
print(sorted_string)  # 输出:['h', 'n', 'o', 'p', 't', 'y']

0