目录
重点
- list 和 dict的操作
- dict的
keys, values, items
函数返回的是views
,不是list
,它们一直反映的是当前dict的状态 - sorted方法可以 给
views
排序
Chap8 List 和 Dictionary
8.1 Lists
list本身是array而不是 linked list.
Operation | Interpretation |
---|---|
L = [] | An empty list |
L = [123, ‘abc’, 1.23, {}] | Four items: indexes 0…3 |
L = [‘Bob’, 40.0, [‘dev’, ‘mgr’]] | Nested sublists |
L = list(‘spam’) | List of an iterable’s items, list of successive integers |
L = list(range(-4, 4)) | |
L[i] | Index, index of index, slice, length |
L[i][j] | |
L[i:j] | |
len(L) | |
L1 + L2 | Concatenate, repeat |
L * 3 | |
for x in L: print(x) | Iteration, membership |
3 in L | |
L.append(4) | Methods: growing |
L.extend([5,6,7]) | |
L.insert(i, X) | Methods: searching |
L.index(X) | |
L.count(X) | |
L.sort() | Methods: sorting, reversing, |
L.reverse() | copying (3.3+), clearing (3.3+) |
L.copy() | |
L.clear() | |
L.pop(i) | Methods, statements: shrinking |
L.remove(X) | |
del L[i] | |
del L[i:j] | |
L[i:j] = [] | |
L[i] = 3 | Index assignment, slice assignment |
L[i:j] = [4,5,6] | |
L = [x**2 for x in range(5)] | List comprehensions and maps (Chapter 4, Chapter 14, Chapter 20) |
list(map(ord, ‘spam’)) |
- 比较排序: sort, reverse; 内置函数
sorted
python3不再支持传入自定义比较函数给sort, 而是传入一个
key=func
来指定transformation
8.2 Dictioanry
Operation | Interpretation |
---|---|
D = {} | Empty dictionary |
D = {‘name’: ‘Bob’, ‘age’: 40} | Two-item dictionary |
E = {‘cto’: {‘name’: ‘Bob’, ‘age’: 40}} | Nesting |
D = dict(name=‘Bob’, age=40) | Alternative construction techniques: |
D = dict([('name', 'Bob'), ('age', 40)]) | keywords, key/value pairs, zipped key/value pairs, key lists |
D = dict(zip(keyslist, valueslist) ) | |
D = dict.fromkeys([‘name’, ‘age’]) | 传入keys和初始值,不传默认为None |
D[‘name’] | Indexing by key |
E[‘cto’][‘age’] | |
'age' in D | Membership: key present test |
D.keys() | Methods: all keys, |
D.values() | all values, |
D.items() | all key+value tuples, |
D.copy() | copy (top-level), |
D.clear() | clear (remove all items), |
D.update(D2) | merge by keys, |
D.get(key, default?) | fetch by key, if absent default (or None), |
D.pop(key, default?) | remove by key, if absent default (or error) |
D.setdefault(key, default?) | fetch by key, if absent set default (or None), |
D.popitem() | remove/return any (key, value) pair; etc. |
len(D) | Length: number of stored entries |
D[key] = 42 | Adding/changing keys |
del D[key] | Deleting entries by key |
list(D.keys()) | Dictionary views (Python 3.X) |
D1.keys() & D2.keys() | |
D.viewkeys(), D.viewvalues() | Dictionary views (Python 2.7) |
D = {x: x*2 for x in range(10)} | Dictionary comprehensions (Python 3.X, 2.7) |
8.3 Dict In Action
collections模块中有额外的 dict 和 list的其他对象,是牺牲性能换取功能的
- 使用dict来模拟 sparsed matrix:
>>> Matrix = {}
>>> Matrix[(2, 3, 4)] = 88
>>> Matrix[(7, 8, 9)] = 99
- dict的键是 mutable对象,包括tuple和int,也可以是用户的自定义对象,只要实现了特定的方法即可。告诉python,这是hashable的
8.4 Dict 在Python3中的变化
- 增加了 dict comprehension
- 使用
keys, values, items
方法,返回的是像list一样的views
而不是真正的list - 使用
in
来判断是否存在
a. dict comprehension
{ x: x**2 for x in [1,2,3]}
b. views
- views对象是iterable
- views保持了dict 对象本来的顺序,并且还支持 集合操作: keys是set-like, values不是,items() 取决于内容是不是hashable的
- views并不是创建之后就保持不变的,而是时刻都反映着原dict对象的内容
keys()
因为返回的是view,没有.sort
函数,所以要排序的话需要变成list,或者使用sorted
函数
# keys() view 的集合操作
>>> K, V
(dict_keys(['c', 'a']), dict_values([3, 1]))
>>> K | {'x': 4} # Keys (and some items) views are set-like
{'c', 'x', 'a'}
# views的 反映原对象特性
>>> K = D.keys()
>>> V = D.values()
>>> list(K) # Views maintain same order as dictionary
['b', 'c', 'a']
>>> list(V)
[2, 3, 1]
>>> del D['b'] # Change the dictionary in place
>>> D
{'c': 3, 'a': 1}
>>> list(K) # Reflected in any current view objects
['c', 'a']
>>> list(V) # Not true in 2.X! - lists detached from dict
[3, 1]