在你创建的列表中,元素的排列顺序常常是无法预测的,因为你并非总能控制用户提供数据的顺序。这虽然在大多数情况下都是不可避免的,但你经常需要以特定的顺序呈现信息。有时候,你希望保留列表元素最初的排列顺序,而有时候又需要调整排列顺序。Python提供了很多组织列表的方式,可根据具体情况选用。
Python为列表提供了一系列的内置函数,如下表所示:
Method | Description |
---|---|
append() | Adds an element at the end of the list |
clear() | Removes all the elements from the list |
copy() | Returns a copy of the list |
count() | Returns the number of elements with the specified value |
extend() | Add the elements of a list (or any iterable), to the end of the current list |
index() | Returns the index of the first element with the specified value |
insert() | Adds an element at the specified position |
pop() | Removes the element at the specified position |
remove() | Removes the first item with the specified value |
reverse() | Reverses the order of the list |
sort() | Sorts the list |
3.3.1 使用方法 sort()对列表进行永久性排序
Python方法sort()让你能够较为轻松地对列表进行排序。假设你有一个汽车列表,并要让其中的汽车按字母顺序排列。为简化这项任务,我们假设该列表中的所有值都是小写的。
# cars.py
cars = ['byd', 'geely', 'lynk&co', 'haval', 'wey']
print(cars)
cars.sort()
print(cars)
方法sort()永久性地修改了列表元素的排列顺序。现在,汽车是按字母顺序排列的,再也无法恢复到原来的排列顺序:
[‘byd’, ‘geely’, ‘lynk&co’, ‘haval’, ‘wey’]
[‘byd’, ‘geely’, ‘haval’, ‘lynk&co’, ‘wey’]
你还可以按与字母顺序相反的顺序排列列表元素,为此,只需向sort()方法传递参数reverse=True。下面的示例将汽车列表按与字母顺序相反的顺序排列:
# cars.py
cars = ['byd', 'geely', 'lynk&co', 'haval', 'wey']
cars.sort(reverse=True)
print(cars)
同样,对列表元素排列顺序的修改是永久性的:
[‘wey’, ‘lynk&co’, ‘haval’, ‘geely’, ‘byd’]
3.3.2 使用函数 sorted()对列表进行临时排序
要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,可使用函数sorted()。函数sorted()让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。
下面尝试对汽车列表调用这个函数。
# cars.py
cars = ['byd', 'geely', 'lynk&co', 'haval', 'wey']
print(cars)
print(sorted(cars))
print(cars)
输出:
[‘byd’, ‘geely’, ‘lynk&co’, ‘haval’, ‘wey’]
[‘byd’, ‘geely’, ‘haval’, ‘lynk&co’, ‘wey’]
[‘byd’, ‘geely’, ‘lynk&co’, ‘haval’, ‘wey’]
由此可见,sorted()函数并未将列表本身进行排序,而是生成了一个临时列表。如果你要按与字母顺序相反的顺序显示列表,也可向函数sorted()传递参数reverse=True。
注:在并非所有的值都是小写时,按字母顺序排列列表要复杂些。决定排列顺序时,有多种解读大写字母的方式,要指定准确的排列顺序,可能比我们这里所做的要复杂。然而,大多数排序方式都基于本节介绍的知识。
3.3.3 倒着打印列表
要反转列表元素的排列顺序,可使用方法reverse()。假设汽车列表是按购买时间排列的,可轻松地按相反的顺序排列其中的汽车:
# cars.py
cars = ['byd', 'geely', 'lynk&co', 'haval', 'wey']
print(cars)
cars.reverse()
print(cars)
输出:
[‘byd’, ‘geely’, ‘lynk&co’, ‘haval’, ‘wey’]
[‘wey’, ‘haval’, ‘lynk&co’, ‘geely’, ‘byd’]
注意,reverse()不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序。
方法reverse()永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse()即可,如:
# cars.py
cars = ['byd', 'geely', 'lynk&co', 'haval', 'wey']
print(cars)
cars.reverse()
print(cars)
cars.reverse()
print(cars)
输出:
[‘byd’, ‘geely’, ‘lynk&co’, ‘haval’, ‘wey’]
[‘wey’, ‘haval’, ‘lynk&co’, ‘geely’, ‘byd’]
[‘byd’, ‘geely’, ‘lynk&co’, ‘haval’, ‘wey’]
3.3.4 确定列表的长度
使用函数len()可快速获悉列表的长度。在下面的示例中,列表包含4个元素,因此其长度为4:
# cars.py
cars = ['byd', 'geely', 'lynk&co', 'haval', 'wey']
print(len(cars))
输出:
4
注:len(cars)等价于cars.len(),其中原理,以后讲到类(class)后再讲。