Python文档学习笔记(5)--数据结构 --列表(1)

列表数据类型还有更多的方法。这里是列表对象方法的清单:

list.append(x)

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

list.extend(L)

将给定列表L中的所有元素附加到原列表a的末尾。相当于 a[len(a):] = L.

list.insert(i, x)

在给定位置插入一个元素。第一个参数为被插入元素的位置索引,因此 a.insert(0, x) 在列表头插入值, a.insert(len(a), x)相当于 a.append(x).

list.remove(x)

删除列表中第一个值为 x 的元素。如果没有这样的项目则会有一个错误。

list.pop([i])

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

list.clear()

删除列表中所有的元素。相当于 del a[:].

list.index(x)

返回列表中第一个值为 x 的元素的索引。如果没有这样的元素将会报错。

list.count(x)

返回列表中 x 出现的次数。

list.sort(key=None, reverse=False)

排序列表中的项 (参数可被自定义, 参看 sorted() ).

list.reverse()

列表中的元素按位置反转。

list.copy()

返回列表的一个浅拷贝。相当于 a[:].

>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print(a.count(333), a.count(66.25), a.count('x'))
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
>>> a.pop()
1234.5
>>> a
[-1, 1, 66.25, 333, 333]

列表作为栈使用

列表方法使得将列表用作堆栈非常容易,其中添加的最后一个元素是可提取的第一个元素(“last-in,first-out”)。使用 append()添加项到栈顶。使用无参的 pop() 从栈顶检出项。例如:

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

列表作为队列使用

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

若要实现一个队列, 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'])

列表推导式

列表推导式提供一个生成列表的简洁方法。应用程序通常会从一个序列的每个元素的操作结果生成新的列表,或者生成满足特定条件的元素的子序列。

>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

注意,上面这个创建(或者覆盖)了一个名为x的变量,它在循环结束时仍然存在。我们可以计算没有任何副作用的平方数列表:

squares = list(map(lambda x: x**2, range(10)))

或者,等价地:

squares = [x**2 for x in range(10)]

上面这个方法更加简明且易读。

列表推导式由一对方括号组成,方括号包含一个表达式,其后跟随一个for子句,然后是零个或多个forif子句。结果将是一个新的列表,其值来自将表达式在其后的forif子句的上下文中求值得到的结果。例如,下面的 listcomp 组合两个列表中不相等的元素:

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

注意这两个代码片段中,forif语句的顺序是如何保持一致的。

如果表达式是一个元组(例如,前面示例中的(x, y)),它必须位于圆括号中。

>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']



>>> # create a list of 2-tuples like (number, square) >>> [(x, x**2) for x in range(6)] [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] >>> # the tuple must be parenthesized, otherwise an error is raised >>> [x, x**2 for x in range(6)] File "<stdin>", line 1, in ? [x, x**2 for x in range(6)] ^ SyntaxError: invalid syntax




>>> # flatten a list using a listcomp with two 'for' >>> vec = [[1,2,3], [4,5,6], [7,8,9]] >>> [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9]

列表推导式可以包含复杂的表达式和嵌套的函数:

>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

嵌套的列表推导式

列表推导式的第一个表达式可以是任何表达式,包括另外一个列表推导式。

考虑下面由三个长度为 4 的列表组成的 3x4 矩阵:

>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

下面的列表推导式将转置行和列:

>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

del 语句

有一个方法可以根据索引而不是值从列表中删除一个元素:del语句。这跟pop()方法不同,后者会返回一个值。del语句也可以用于从列表中删除片段或清除整个列表(先前我们通过将一个空列表赋值给这个片段来达到此目的)。例如:

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

del 也可以用于删除整个变量︰

>>> del a

 

 

 

 

 

 

posted @ 2019-05-22 13:17  IMWU  阅读(244)  评论(0编辑  收藏  举报