5. 数据结构 python v2.7.8 官方教程
2016-01-11 17:00:53

list.append(x)

list.extend(L)

list.insert(ix)

list.remove(x)

list.pop([i])

list.index(x)

list.count(x)

list.sort(cmp=Nonekey=Nonereverse=False)

list.reverse()

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

### 5.1.1. 用列表作为栈

`>>> 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. 用列表作为队列

`>>> 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. 函数式编程工具

filter(function, sequence)返回的序列由function(item)结果为真的元素组成。如果sequence是一个字符串元组，结果将是相同的类型；否则，结果将始终是一个列表例如，若要计算一个不能被2和3整除的序列：

`>>> def f(x): return x % 2 != 0 and x % 3 != 0 ... >>> filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23] `

map(function, sequence) 为序列中的每一个元素调用 function(item) 函数并返回结果的列表。例如，计算列表中所有元素的立方值：

`>>> def cube(x): return x*x*x ... >>> map(cube, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] `

`>>> seq = range(8) >>> def add(x, y): return x+y ... >>> map(add, seq, seq) [0, 2, 4, 6, 8, 10, 12, 14] `

reduce(function, sequence) 只返回一个值，它首先以序列的前两个元素调用函数 function，然后再以返回的结果和下一个元素继续调用，依此执行下去。例如，若要计算数字 1 到 10 的总和：

`>>> def add(x,y): return x+y ... >>> reduce(add, range(1, 11)) 55 `

`>>> def sum(seq): ...  def add(x,y): return x+y ...  return reduce(add, seq, 0) ... >>> sum(range(1, 11)) 55 >>> sum([]) 0 `

### 5.1.4. 列表推导式

`>>> 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)] `

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

`>>> 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 [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.1. 嵌套的列表推导式

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

`>>> 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(*matrix) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] `

## 5.2. 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 `

## 5.3. 元组和序列

`>>> t = 12345, 54321, 'hello!' >>> t[0] 12345 >>> t (12345, 54321, 'hello!') >>> # Tuples may be nested: ... u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) >>> # Tuples are immutable: ... t[0] = 88888 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> # but they can contain mutable objects: ... v = ([1, 2, 3], [3, 2, 1]) >>> v ([1, 2, 3], [3, 2, 1]) `

`>>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',) `

`>>> x, y, z = t `

## 5.4. 集合

Python还包含一个数据类型用于集合集合中的元素没有顺序且不会重复。集合的基本用途有成员测试和消除重复的条目。集合对象还支持并集、交集、差和对称差等数学运算。

`>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruit = set(basket) # create a set without duplicates >>> fruit set(['orange', 'pear', 'apple', 'banana']) >>> 'orange' in fruit # fast membership testing True >>> 'crabgrass' in fruit False >>> # Demonstrate set operations on unique letters from two words ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a set(['a', 'r', 'b', 'c', 'd']) >>> a - b # letters in a but not in b set(['r', 'd', 'b']) >>> a | b # letters in either a or b set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l']) >>> a & b # letters in both a and b set(['a', 'c']) >>> a ^ b # letters in a or b but not both set(['r', 'd', 'b', 'm', 'z', 'l']) `

`>>> a = {x for x in 'abracadabra' if x not in 'abc'} >>> a set(['r', 'd']) `

## 5.5. 字典

Python内建的另一种有用的数据类型是字典（见映射类型 — 字典)。在其它语言中字典有时被称为“associative memories” 或者 “associative arrays”。与序列不同，序列由数字做索引，字典由 key 做索引，key可以是任意不可变类型；字符串和数字常用来做key。如果元组只包含字符串、 数字或元组，此元组可以用作key；如果元组直接或间接地包含任何可变对象，那么它不能用作key。不能用list作为key，因为列表可以用索引、切片或者append()extend()方法原地修改。

`>>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098} >>> tel['jack'] 4098 >>> del tel['sape'] >>> tel['irv'] = 4127 >>> tel {'guido': 4127, 'irv': 4127, 'jack': 4098} >>> tel.keys() ['guido', 'irv', 'jack'] >>> 'guido' in tel True `

dict()构造函数直接从键-值对序列创建字典：

`>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127} `

`>>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36} `

`>>> dict(sape=4139, guido=4127, jack=4098) {'sape': 4139, 'jack': 4098, 'guido': 4127} `

## 5.6. 遍历的技巧

`>>> for i, v in enumerate(['tic', 'tac', 'toe']): ...  print i, v ... 0 tic 1 tac 2 toe `

`>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ...  print 'What is your {0}?  It is {1}.'.format(q, a) ... What is your name?  It is lancelot. What is your quest?  It is the holy grail. What is your favorite color?  It is blue. `

`>>> for i in reversed(xrange(1,10,2)): ...  print i ... 9 7 5 3 1 `

`>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ...  print f ... apple banana orange pear `

`>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.iteritems(): ...  print k, v ... gallahad the pure robin the brave `

`>>> words = ['cat', 'window', 'defenestrate'] >>> for w in words[:]: # Loop over a slice copy of the entire list. ...  if len(w) > 6: ...  words.insert(0, w) ... >>> words ['defenestrate', 'cat', 'window', 'defenestrate'] `

## 5.7. 深入条件控制

while 和 if 语句中使用的条件可以包含任意的操作，而不仅仅是比较。

`>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' >>> non_null = string1 or string2 or string3 >>> non_null 'Trondheim' `

## 5.8. 序列和其它类型的比较

`(1, 2, 3) < (1, 2, 4) [1, 2, 3] < [1, 2, 4] 'ABC' < 'C' < 'Pascal' < 'Python' (1, 2, 3, 4) < (1, 2, 4) (1, 2) < (1, 2, -1) (1, 2, 3) == (1.0, 2.0, 3.0) (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) `