【Python】Collection - list

Posted by 西维蜀黍 on 2019-11-01, Last Modified on 2023-09-12

list 的常用方法

  • list.remove(x) - 移除列表中第一个值为 x 的元素。如果没有这样的元素,则抛出 ValueError 异常。

  • list.pop([i]) - 删除列表中给定位置的元素并返回它。如果没有给定位置,a.pop() 将会删除并返回列表中的最后一个元素。( 方法签名中 i 两边的方括号表示这个参数是可选的,而不是要你输入方括号。你会在 Python 参考库中经常看到这种表示方法)。

  • list.clear() - 删除列表中所有的元素。相当于 del a[:]

  • list.index(x[, start[, end]]) - 返回列表中第一个值为 x 的元素的从零开始的索引。如果没有这样的元素将会抛出 ValueError 异常。可选参数 startend 是切片符号,用于将搜索限制为列表的特定子序列。返回的索引是相对于整个序列的开始计算的,而不是 start 参数。

  • list.count(x) - 返回元素 x 在列表中出现的次数。

  • list.sort(key=None, reverse=False) - 对列表中的元素进行排序(参数可用于自定义排序,解释请参见 sorted())。

  • list.reverse() - 反转列表中的元素。

  • list.copy() - 返回列表的一个浅拷贝。相当于 a[:]

列表方法示例:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

你可能已经注意到,像 insertremove 或者 sort 方法,只修改列表,没有打印出返回值——它们返回默认值 None 。这是Python中所有可变数据结构的设计原则。

你可能会注意到的另一件事是并非所有数据或可以排序或比较。 例如,[None, 'hello', 10] 就不可排序,因为整数不能与字符串比较,而 None 不能与其他类型比较。 并且还存在一些没有定义顺序关系的类型。 例如,3+4j < 5+7j 就不是一个合法的比较。

初始化 list

>>> [0]*5
[0, 0, 0, 0, 0]

循环 list

如果要对list实现类似Java那样的下标循环怎么办?Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:

>>> for i, value in enumerate(['A', 'B', 'C']):
...     print(i, value)
...
0 A
1 B
2 C

通过索引获取子元素

用索引来访问list中每一个位置的元素,记得索引是从0开始的:

>>> classmates[0]
'Michael'
>>> classmates[1]
'Bob'
>>> classmates[2]
'Tracy'
>>> classmates[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

当索引超出了范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(classmates) - 1

如果要取最后一个元素,除了计算索引位置外,还可以用-1做索引,直接获取最后一个元素:

>>> classmates[-1]
'Tracy'

以此类推,可以获取倒数第2个、倒数第3个:

>>> classmates[-2]
'Bob'
>>> classmates[-3]
'Michael'
>>> classmates[-4]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

当然,倒数第4个就越界了。

也可以通过指定 index,倒着取元素:

>>> a
[1, 2, 3]
>>> n = 1
>>> a[~n]
2

增加元素

  • list.append(x) - 在列表的末尾添加一个元素。相当于 a[len(a):] = [x]

  • list.extend(iterable) - 使用可迭代对象中的所有元素来扩展列表。相当于 a[len(a):] = iterable

  • list.insert(i, x) - 在给定的位置插入一个元素。第一个参数是要插入的元素的索引,所以 a.insert(0, x) 插入列表头部, a.insert(len(a), x) 等同于 a.append(x)

>>> a = [1,2]
>>> a.extend([3,2])
>>> a
[1, 2, 3, 2]
>>> a.append(4)
>>> a.append([4,5])
>>> a
[1, 2, 3, 2, 4, [4, 5]]

子 list 获取

>>> a = [0,1,2,3,4,5,6,7]
>>> a[:2]
[0, 1]
# 从索引为 -1的元素开始取数据,到 list 的末尾,而索引为 -1的元素就是 7
>>> a[-1:]
[7]
>>> a[-2:]
[6, 7]

# 当第二个数字为负数,表示截取到该位置时停止,索引为-2表示从末尾往头部数,第 2 个元素(索引从 1 开始)
# 索引从 -1 开始,-1、-2...
>>> a[:-2]
[0, 1, 2, 3, 4, 5]
>>> a[:-1]
[0, 1, 2, 3, 4, 5, 6]

Misc

# append list
>>> [1] + [2,3,]
[1, 2, 3]
>>> [1] + [2,3]
[1, 2, 3]

# sort
>>> sorted([1,2,4,3])
[1, 2, 3, 4]

list 作为栈使用

列表方法使得列表作为堆栈非常容易,最后一个插入,最先取出(“后进先出”)。要添加一个元素到堆栈的顶端,使用 append() 。要从堆栈顶部取出一个元素,使用 pop() ,不用指定索引。例如

>>> stack = [3, 4, 5]
# push
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
# pop (return and remove the first element)
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

# get the last element
>>> stack[-1]
4

list 作为队列使用

列表也可以用作队列,其中先添加的元素被最先取出 (“先进先出”);然而列表用作这个目的相当低效。因为在列表的末尾添加和弹出元素非常快,但是在列表的开头插入或弹出元素却很慢 (因为所有的其他元素都必须移动一位)。

若要实现一个队列, collections.deque 被设计用于快速地从两端操作。例如

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

Reference