使用sort()方法对列表进行永久性排序及临时排序

来源:互联网 发布:mysql 前后空格为什么 编辑:程序博客网 时间:2024/06/05 16:49

Python从零开始自学——教材:《Python编程从入门到实践——————Eric Matthes》
Windows环境下——VScode编辑器

3.3组织列表:(遇到困扰)
3.3.1使用sort()方法对列表进行永久性排序及临时排序
先看永久性排序代码——书本案例。
cars=['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
cars.sort(reverse=True)
print(cars)

临时排序代码如下:

cars=['bmw','audi','toyota','subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)

输出结果:Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']


Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']


Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']


重点:如果你要按字母顺序相反的顺序显示列表,也可向函数sorted()传递参数reverse=True.

如何传递?

方法如下

places=['Paris','Boston','Houston','London','Tokyo']
print(places)
print(sorted(places))
print(places)
print(sorted(places,reverse=True))
输出结果:

['Paris', 'Boston', 'Houston', 'London', 'Tokyo']
['Boston', 'Houston', 'London', 'Paris', 'Tokyo']
['Paris', 'Boston', 'Houston', 'London', 'Tokyo']
['Tokyo', 'Paris', 'London', 'Houston', 'Boston']

向函数sorted()传递reverse=True即sorted(list,reverse=True)即可。


谢谢观看。



阅读全文
0 0