python对列表进行永久性或临时排序的方法
python对列表进行永久性或临时排序的方法
1、对列表进行永久性排序:使用方法sort()
sort()方法:用于将列表中的元素进行排序。默认按升序排列。
也可以向sort()方法传递参数reverse=True反向排序。
num=[22,11,45,520,987,8]
num.sort()
print(num)
num.sort(reverse=True)
print(num)
输出
[8,11,22,45,520,987]
[987,520,45,22,11,8]
2、对列表进行临时排序:使用方法sorted()
要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,它使用函数sorted()。
该函数能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列排序。
cars=['bmw','audi','toyota','subaru']
print('Hereistheoriginallist:',cars)
print('Hereisthesortedlist:',sorted(cars))
Hereistheoriginallist:['bmw','audi','toyota','subaru']
Hereisthesortedlist:['audi','bmw','subaru','toyota']
以上就是python对列表进行永久性或临时排序的方法,希望能对大家有所帮助。更多Python学习教程请关注IT培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
python中mat是什么意思?
python中mat是什么意思?本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。python的numpy库提供矩阵运算的功能,因此我们在需要矩阵运...详情>>
2023-11-10 23:22:48
python上下文管理的使用场景
python上下文管理的使用场景本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、上下文管理的使用场景凡是要在代码块前后插入代码的...详情>>
2023-11-10 20:07:44
python常量折叠是什么
python常量折叠是什么1、概念所谓常量折叠,指的是在编译时就查找并计算常量表达式,而不是在运行时再对其进行计算,从而会使运行时更加精简和...详情>>
2023-11-10 19:11:50
pythonTCP与UDP的不同点分析
python中TCP与UDP的不同点分析(推荐操作系统:windows7系统、Python3.9.1、DELLG3电脑。)1、不同点面向连接(确认有创建三方交握,连接已创建才...详情>>
2023-11-10 18:16:05热门推荐
技术干货






