python cookbook一些知識(shí)點(diǎn)
一、python數(shù)據(jù)結(jié)構(gòu)與算法
- python解壓賦值
data = ['ACME', 50, 91.1, (2012, 12, 21)]
name, shares, *price = data
print(price)
a1, b1, c1, (d1, e1, f1) = data
print(d1, f1)
- 字符解壓賦值
data = "hello"
a, *b, c = data
print(c)
結(jié)果:o
- 占位可以用_觉痛,解壓多個(gè)值可用*
_, *b1, c1, d1 = data
print(b1)
- 解壓多個(gè)值,好用的方法
records = [
["foo", 1, 2],
["fo", 1],
["foo", 3, 4],
]
def fn(x, y):
print("foo", x, y)
for flag, *l in records:
if flag == "foo":
x, y = l
fn(x, y)
- 解壓賦值茵休,雙\ 代表轉(zhuǎn)義
str_r = r"H:\Sublime\User\GoSublime\windows-x32"
a, *b, c = str_r.split("\\")
print(a, c)
- 有長(zhǎng)度隊(duì)列,pop后進(jìn)先出
from collections import deque
q = deque(maxlen=3)
q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.pop()
q.appendleft(6) #在右邊增加
- 查找n最大最小值
import heapq
list_a = [1, 6, 7, 3, 5, 8, 3]
print(heapq.nlargest(3, list_a))
print(heapq.nsmallest(3, list_a))
print(heapq.nlargest(len(list_a), list_a))
import heapq
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
print(heapq.nlargest(3, portfolio, key=lambda i: i["shares"]))
堆排序 會(huì)把最小元素提到最前面
import heapq
list_a = [1, 6, 7, 3, 5, 8, 3, -2, -3, -1]
heapq.heapify(list_a)
print(list_a)
扔掉最前面一個(gè)元素
heapq.heappop(list_a)
print(list_a)
heapq.heappop(list_a)
print(list_a)
heapq.heappop(list_a)
扔掉最小元素
print(heapq.heappop(list_a))
print(list_a)
- 多映射值dict的創(chuàng)建
from collections import defaultdict
d = defaultdict(set)
d["a"].add(1)
d["a"].add(2)
d['b'].add(1)
d['b'].add(1)
print(d)
print(d["a"])
- 有序字典的創(chuàng)建
from collections import OrderedDict
od = OrderedDict()
od["three"] = 3
od["four"] = 4
od["one"] = 1
od["two"] = 2
print(od)
有序字典秧饮,不過內(nèi)存消耗大