列表
列表也就是list,可以用方括号来表示:
In [40]: ages = [ 10, 14, 18, 20 ,25]
In [41]: ages
Out[41]: [10, 14, 18, 20, 25]
list有一些非常有用的方法,比如append,extend,insert,remove,pop,index,count,sort,reverse,copy等。
举个例子:
>>> 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'
列表作为栈使用
栈的特点是后进先出,而列表为我们提供了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]
列表作为队列使用
队列的特点是先进先出,但是使用列表在队列头部插入元素是很慢的,因为需要移动所有的元素。
>>> 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'])
列表推导式
要创建列表,通常的做法是使用for循环,来遍历列表,并为其设置值:
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
或者我们可以使用列表推导式来更加简洁的生成列表:
squares = [x**2 for x in range(10)]
列表推导式的结构是由一对方括号所包含的以下内容:一个表达式,后面跟一个 for 子句,然后是零个或多个 for 或 if 子句。
列表推导式将会遍历for字句中的元素,并且使用表达式来求值,将生成的元素作为新的列表元素返回。
看一个复杂点的:
>>> [(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)]
列表推导式还可以嵌套,假如我们有一个矩阵:
>>> 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]]
或者使用更加简单的zip函数:
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
del
删除列表中的某个元素可以使用del。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 a