
python对列表进行永久性或临时排序的方法
1、对列表进行永久性排序:使用方法 sort()
sort() 方法:用于将列表中的元素进行排序。默认按升序排列。
也可以向 sort() 方法传递参数 reverse = True 反向排序。
1 2 3 4 5 | num = [22,11,45,520,987,8]
num.sort()
print (num)
num.sort(reverse=True)
print (num)
|
输出
1 2 | [8, 11, 22, 45, 520, 987]
[987, 520, 45, 22, 11, 8]
|
2、对列表进行临时排序:使用方法 sorted()
要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,它使用函数 sorted()。
该函数能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列排序。
1 2 3 | cars = [ 'bmw' , 'audi' , 'toyota' , 'subaru' ]
print ( 'Here is the original list:' ,cars)
print ( 'Here is the sorted list:' ,sorted(cars))
|
1 2 | Here is the original list: [ 'bmw' , 'audi' , 'toyota' , 'subaru' ]
Here is the sorted list: [ 'audi' , 'bmw' , 'subaru' , 'toyota' ]
|