在创建列表的时候,列表中元素的排列顺序是无法预测的,有时候需要根据特定的顺序排列,下面提供几种方式对其进行排序。
1、使用sort()对列表进行永久性排序:
这个方法永久性修改了列表元素的排序:
“`python
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
cars.sort()
print(cars)
“`
上面的粒子是按照字母排序来的。
如果要逆序呢:
“`python
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
cars.sort(reverse=True)
print(cars)
“`
这样就按照逆序的方式排列出来。这两种方式的排序都是永久性改变的。
2、使用函数sorted()对列表进行临时排序
要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,可使用函数sorted()。函数sorted()让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。同样还是用例子来说明:
“`python
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)
“`
注意,调用函数sorted()后,列表元素的排列顺序并没有变。如果你要按与字母顺序相反的顺序显示列表,也可向函数sorted()传递参数reverse=True。
3、逆序打印列表使用reverse()
“`python
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
print(cars)
cars.reverse()
print(cars)
“`
4、确定列表的长度使用函数len()
“`python
cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
print(len(cars))
“`
这样就可以得到列表的长度,也就是里面有几个元素。
转载请注明:XAMPP中文组官网 » python入门学习系列教程七 组织列表