可以使用 Python 内置函数 sort() 来对列表进行升序排序:

my_list = [3, 1, 4, 2, 5]
my_list.sort()
print(my_list)  # 输出 [1, 2, 3, 4, 5]

也可以使用 sorted() 函数来对列表进行升序排序,它返回一个新的已排序的列表:

my_list = [3, 1, 4, 2, 5]
new_list = sorted(my_list)
print(new_list)  # 输出 [1, 2, 3, 4, 5]

需要注意的是,sort()sorted() 函数都是对原有列表进行排序,如果需要保留原有列表,可以使用切片操作来复制一份列表进行排序:

my_list = [3, 1, 4, 2, 5]
new_list = my_list[:]
new_list.sort()
print(new_list)  # 输出 [1, 2, 3, 4, 5]
print(my_list)   # 输出 [3, 1, 4, 2, 5]
Python 列表数字升序排序:sort() 和 sorted() 函数

原文地址: https://www.cveoy.top/t/topic/m88t 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录