可以使用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 list 数字升序排列

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

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