![](https://csdnimg.cn/release/download_crawler_static/87216204/bg9.jpg)
cars = ['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
output:
['audi','bmw','subaru','toyota']
如果想按字母顺序倒序排序,可以给 sort()方法传参 reverse=true,如:
cars.sort(reverse=true)
3.3.2 使用函数 sorted()对列表临时排序
要保留列表元素原来的排列顺序,同时以特定的顺序呈现他们,可使用函数 sorted()。
cars = ['bmw','audi','toyota','subaru']
print(sorted(cars))
output:
['audi','bmw','subaru','toyota']
如果想要按字母相反的顺序显示列表,也可向 sorted()传递参数 reverse = True
3.3.3 倒着打印列表
list.reverse()
cars = ['bmw','audi','toyota','subaru']
cars.reverse()
print(cars)
output:
['subaru','toyota','audi','bmw']
3.3.4 确定列表的长度
len()可快速获悉列表的长度,长度为元素的个数。Len()也能得到字符串的字符数。