Python3 官方文档翻译

这章会更详细地描述了一些你已经学过的知识,同时添加一些新东西。

5.1 List进阶

下面是关于List的所有方法

list.append(x)
将元素添加至列表尾,相当于a[len(a):] [x]
 
list.extend(L)
通过将L中所有元素添加至列表尾来扩展list,相当于a[len(a):] L
 
list.insert(i,x)
在指定位置插入元素。第一个参数是插入位置前一个的下标,a.insert(0,x)是在列表头插入,a.insert(len(a),x)相当于a.append(x)
 
list.remove(x)
移除值为x的第一个元素。如果没有则返回一个error
 
list.pop([i])
弹出指定位置的元素。如果不指定下标,a.pop()将弹出最后一个元素。(方法体中,i左右的方括号 [ ] 代表这个参数是可选的,是不你需要在那个位置输入的,在Python Library Reference中你将频繁地看到这个符号)
 
list.clear()
移除所有的元素
 
list.index(x)
返回第一个值为x的元素的下标。如果没有则返回一个error
 
list.count(x)
计算x在list中出现的次数
 
list.sort(key=None, reverse=False)
将list中的元素原地排序(参数可以用来自定义排序,详情查看sorted()方法)
 
list.reverse()
原地倒置list中元素
 
list.copy()
返回list的一个影子拷贝(浅拷贝),相当于 a[:]
 
用一个例子来说明list的大多数用法
>>> 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]
list的用法

你可能会注意到像insert、remove或sort这样的方法只修改了List而没有返回值——其实他们都返回了空值None。这是Python中对所有可变数据结构的一个设计原则

5.1.1 像Stacks那样使用Lists

List的方法让它很容易像Stack那样被使用,最后一个加入的元素第一个被删除("后进先出"原则 )。使用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]

5.1.2 像Queues那样使用Lists

同样的,List的方法也使它很容易像queue那样被使用,第一个加入的元素第一个被删除("先进先出"原则)。但是,List在这种用法下并不高效。尽管从List末尾添加或是删除元素是很快的,但从List起始位置插入或弹出元素却是慢的(因为需要所有其他的元素依次移动一个位置)
因此,推荐使用collections.deque来实现 queue,它被设计成从两端都可以快速地添加和移除元素。
>>> 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'])

5.1.3 列表生成式

列表生成式是创建list的简明方法。通常,如果应用要创建新的list,需要将某些操作应用于序列或是iterable的类型的每个元素,或是找出符合特定条件的元素的子序列。
例如,如果我们要创建一个平方数列表,我们需要:
>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

值得注意的是,我们在loop完成后创建了(甚至可能覆盖)一个名称为 x 的变量。实际上,我们可以通过一行的列表生成式来清晰安全地创建:

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

或是等价于:

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

这无疑是更加精确和可读的。

这个列表生成式在圆括号后紧跟了一个for从句,然后是零或多个for 或if 从句,并返回表达式所产生的新list。

例如这个返回结果包含了两个list中互不相等的元素对。

>>> [(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)]

这等价于:

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

注意for和if的顺序在这两段代码中是相同的。

就像上例中的(x, y)那样,如果返回结果是一个tuple元组,那么需要在两端加上括号。

>>> 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']

5.1.4 嵌套的列表生成式

下面是一个3*4的矩阵实现:
>>> 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]]

使用for来实现内嵌方法,它也可以是这样的:

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

任何的列表生成式都不用 ,它将会是这样的:

>>> transposed = []
>>> for i in range(4):
...     # the following 3 lines implement the nested listcomp
...     transposed_row = []
...     for row in matrix:
...         transposed_row.append(row[i])
...     transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

然而在现实世界中,我们并不希望写出如此复杂的语句。说了那么多,其实使用内置的zip()方法就可以轻松解决:

>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
 
 
 
 
 
原文地址:https://www.cnblogs.com/andrew-chen/p/4949480.html