阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
1. dict: Python 3.7 起保证插入顺序
1.1 Create a dict
d = {'Jack':1557, 'Tom':1320, 'Rose':10}
print(d['Jack'])1557
d = dict([('Jack', 1557), ('Tom', 1320), ('Rose', 10)])
print(d){'Jack': 1557, 'Tom': 1320, 'Rose': 10}
1.2 Look-up
grades = {'Ana':'B', 'John':'A+', 'Denise':'A', 'Katy':'A'}1.2.1 dict[key]
grades['Sylvan']KeyError: 'Sylvan'
1.2.2 避免KeyError
- 用get()
dict.get(key[,default])grades.get('Sylvan', 'none')'none'
- 用in判断
if 'Sylvan' in grades:
print(grades['Sylvan'])
else:
print('None')None
1.3 update(): Add a new entry
dict1 = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict1.update(dict2)
print(dict1){'Name': 'Zara', 'Age': 7, 'Sex': 'female'}
1.3 items(), keys(), values()
d = dict([('Jack', 1557), ('Tom', 1320), ('Rose', 10)])
print(d.items())
for k, v in d.items():
print(k, v)dict_items([('Jack', 1557), ('Tom', 1320), ('Rose', 10)])
Jack 1557
Tom 1320
Rose 10
print(d.keys())
print(d.values())dict_keys(['Jack', 'Tom', 'Rose'])
dict_values([1557, 1320, 10])
1.4 删除
1.4.1 pop()
dict.pop(key[,default])- key: 要删除的key
- default: 如果没有 key,返回 default 值
- 返回被删除的value
d = dict([('Jack', 1557), ('Tom', 1320), ('Rose', 10)])
print(d.pop('Jack'))
print(d)1557
{'Tom': 1320, 'Rose': 10}
print(d.pop('Morse'))KeyError: 'Morse'
print(d.pop('Morse', 'No such key'))No such key
1.4.2 del
d = dict([('Jack', 1557), ('Tom', 1320), ('Rose', 10)])
del d['Tom']
print(d){'Jack': 1557, 'Rose': 10}
del d['Tom']
print(d)KeyError: 'Tom'
1.5 Requirement for keys
keys:
- must be unique
- hashable 类型:list、set 不可用;frozenset 可用,tuple 的每个成员也必须可哈希
x = {[1]: 10}TypeError: unhashable type: 'list'
y = {(1, 2): 10}
print(y){(1, 2): 10}
1.6 TC of different operations on dict and list
| Operation | Dictionary | List |
|---|---|---|
| Search | ||
| Add | ||
| Delete | ||
| Update |
- SC of all operations above for dict is
整理注: 哈希查找/插入为通常平均复杂度,列表尾部追加是摊还复杂度;表中O(n)空间指整个容器占用,不是每次查找的额外空间。
2. set: 不保证顺序的不重复元素序列
2.1 Create a set
s = set([1, 1, 2, 3]) # 去重
print(s){1, 2, 3}
s = {'b', 'a', 'c'}
print(s){'c', 'b', 'a'}
用于创建set须为可迭代对象,且元素可哈希
s = set(1, 2, 3) # 错误写法TypeError: set expected at most 1 argument, got 3
s = set([1, 2, 3]) # 正确写法
print(s){1, 2, 3}
s = set('abc')
print(s)
# 注意区别:
s = set(['abc'])
print(s){'c', 'b', 'a'}
{'abc'}
2.2 添加元素
2.2.1 add(): one element
s = set('abc') # 不保证顺序
s.add(1)
print(s){1, 'c', 'b', 'a'}
2.2.2 update(): multiple elements
s = set('abc')
s.update({'d', 'e'})
print(s){'c', 'b', 'a', 'e', 'd'}
2.3 移除元素
2.3.1 remove(): 如果元素不存在,则会发生错误
s = {1, 2, 3, 4}
s.remove(1)
print(s){2, 3, 4}
s.remove(1)KeyError: 1
2.3.2 discard(): 如果元素不存在,不会发生错误
s = {1, 2, 3, 4}
s.discard(1)
print(s){2, 3, 4}
s.discard(1)2.3.3 pop(): delete one arbitrary element(不保证随机抽样)
s = {1, 2, 3, 4}
s.pop()
print(s){2, 3, 4}
2.3.4 clear(): clear all elements
s = {1, 2, 3, 4}
s.clear()
print(s)set()
2.4 union(), difference(), intersection()
2.4.1 union()
x = {1, 2, 3}
y = {2, 3, 4, 5}
print(x.union(y)){1, 2, 3, 4, 5}
# Or
print(x | y){1, 2, 3, 4, 5}
2.4.2 difference()
x = {1, 2, 3}
y = {2, 3, 4, 5}
print(x.difference(y))
print(y.difference(x)){1}
{4, 5}
# Or
print(x - y)
print(y - x){1}
{4, 5}
2.4.3 intersection()
x = {1, 2, 3}
y = {2, 3, 4, 5}
print(x.intersection(y)){2, 3}
# Or
print(x & y){2, 3}
2.5 Other operators
x = {1, 2, 3}
y = {2, 3}print(x == y)False
print(x != y)True
print(x <= y) # x is subset of yFalse
print(x < y) # x is proper subset of yFalse
print(x >= y) # x is superset of yTrue
print(x > y) # x is proper superset of yTrue
3. Palindromic testing
给定一个字符串,判断这个字符串是否可以改写成回文。
- 如果string长度为偶数: 所有字符出现频率都必须为偶数
- 如果string长度为奇数: 只能有一个字符出现奇数次
结论: 最多只能有一个出现奇数次的字符
def is_palindromic(word):
freq = {}
for letter in word:
if letter in freq:
freq[letter] += 1
else:
freq[letter] = 1
print(freq)
odd_cnt = 0
for value in freq.values():
if value % 2 == 1:
odd_cnt += 1
if odd_cnt > 1:
return False
return True
print(is_palindromic('ababbcc'))
print(is_palindromic('abarbbcdc')){'a': 2, 'b': 3, 'c': 2}
True
{'a': 2, 'b': 3, 'r': 1, 'c': 2, 'd': 1}
False