快速入门
Python 有一些复合数据类型, 用于组合值. 最常用的是 list(列表)), 为中括号之间的逗号分隔的值. 列表的元素可以是多种类型, 但是通常是同一类型.
- >>> squares = [1, 4, 9, 16, 25]
- >>> squares
- [1, 4, 9, 16, 25]
像字符串和其他序列类型, 列表可支持切片和索引:
- >>> squares[0] # indexing returns the item
- 1
- >>> squares[-1]
- 25
- >>> squares[-3:] # slicing returns a new list
- [9, 16, 25]
切片返回新的列表, 下面操作返回列表 a 的浅拷贝:
- >>> squares[:]
- [1, 4, 9, 16, 25]
列表还支持连接:
- >>> squares + [36, 49, 64, 81, 100]
- [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
字符串是不可改变的, 列表是可变的.
- >>> cubes = [1, 8, 27, 65, 125] # something's wrong here
- >>> 4 ** 3 # the cube of 4 is 64, not 65!
- 64
- >>> cubes[3] = 64 # replace the wrong value
- >>> cubes
- [1, 8, 27, 64, 125]
append()方法可以添加元素到尾部:
- >>> cubes.append(216) # add the cube of 6
- >>> cubes.append(7 ** 3) # and the cube of 7
- >>> cubes
- [1, 8, 27, 64, 125, 216, 343]
也可以对切片赋值, 此操作甚至可以改变列表的尺寸, 或清空它:
- >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
- >>> letters
- ['a', 'b', 'c', 'd', 'e', 'f', 'g']
- >>> # replace some values
- >>> letters[2:5] = ['C', 'D', 'E']
- >>> letters
- ['a', 'b', 'C', 'D', 'E', 'f', 'g']
- >>> # now remove them
- >>> letters[2:5] = []
- >>> letters
- ['a', 'b', 'f', 'g']
- >>> # clear the list by replacing all the elements with an empty list
- >>> letters[:] = []
- >>> letters
- []
内置函数 len() 同样适用于列表:
- >>> letters = ['a', 'b', 'c', 'd']
- >>> len(letters)
- 4
支持嵌套列表(包含其它列表的列表), 例如:
- >>> a = ['a', 'b', 'c']
- >>> n = [1, 2, 3]
- >>> x = [a, n]
- >>> x
- [['a', 'b', 'c'], [1, 2, 3]]
- >>> x[0]
- ['a', 'b', 'c']
- >>> x[0][1]
- 'b'
深入列表
列表的所有方法如下:
方法 | 功能 |
---|---|
list.append(x) | 附加元素到列表末端,相当于 a[len(a):] = [x]。 |
list.extend(L) | 附加列表 L 的内容到当前列表后面,相当于 a[len(a):] = L 。 |
list.insert(i, x) | 在指定位置 i 插入 x。i 表示插入位置,原来的 i 位置如果有元素则往后移动一个位置,例如 a.insert(0, x) 会插入到列表首部,而 a.insert(len(a), x) 相当于 a.append(x)。 |
list.remove(x) | 删除列表中第一个值为 x 的元素。如果没有就报错。 |
list.pop([i]) | 删除列表指定位置的元素,并将其返回该元素。如果没有指定索引针对最后一个元素。方括号表示 i 是可选的。 |
list.clear() | 从列表中删除所有元素。相当于 del a[:] |
list.index(x[, start[, end]]) | 返回第一个值为 x 的元素的索引。如果没有则报错。 |
list.count(x) | 返回 x 在列表中出现的次数。 |
list.sort(cmp=None, key=None, reverse=False) | 就地对列表中的元素进行排序。 |
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'
也许大家会发现像 insert,remove 或者 sort 这些修改列表的方法没有打印返回值 - 它们返回 None. 参考 https://docs.python.org/3/tutorial/datastructures.html#id3 . 这是所有可变的数据类型的统一的设计原则.
把链表当作堆栈使用
堆栈后进先出. 进使用 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]
列表推导:
squares = [x**2 for x in range(10)]
等价于 squares = map(lambda x: x**2, range(10)), 但可读性更好, 更简洁.
列表推导式包含在放括号中, 表达式后有 for 子句, 之后可以有零或多个 for 或 if 子句. 结果是基于表达式计算出来的列表:
- >>> [(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)]
如果想要得到元组 (例如, 上例的 (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']
嵌套列表推导式
有如下嵌套列表:
- >>> 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()内置函数更好:
- >>> list(zip(*matrix))
- [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
小结: 创建列表的常用方法:
1, 中括号: 比如 data = [4, 9, 2, 8, 3, 2, 5, 4, 2] 2,range: 比如 list(range(100)) 3, 列表推导式: 比如[expression for variable in sequence], 实际是中括号的变种.
列表相关的内置函数 len,max,min,sum,sorted,list, 请在内置函数中学习. 后面的习题会覆盖这些函数.
来源: http://www.jianshu.com/p/97319a43ba35