读书笔记:LearningPython第五版 (第八章 List和Dictionary)

重点

  1. list 和 dict的操作
  2. dict的 keys, values, items 函数返回的是 views,不是list,它们一直反映的是当前dict的状态
  3. sorted方法可以 给 views排序

Chap8 List 和 Dictionary

8.1 Lists

list本身是array而不是 linked list.

OperationInterpretation
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 + L2Concatenate, 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] = 3Index 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

OperationInterpretation
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 DMembership: 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] = 42Adding/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中的变化

  1. 增加了 dict comprehension
  2. 使用keys, values, items方法,返回的是像list一样的views而不是真正的list
  3. 使用in来判断是否存在

a. dict comprehension

{ x: x**2 for x in [1,2,3]}

b. views

  1. views对象是iterable
  2. views保持了dict 对象本来的顺序,并且还支持 集合操作: keys是set-like, values不是,items() 取决于内容是不是hashable的
  3. views并不是创建之后就保持不变的,而是时刻都反映着原dict对象的内容
  4. 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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值