1-基础部分-1-Python

Chapter 1

1.1 分解序列

需要元素数量匹配,除了元组和列表,其余可迭代也可执行。

1
2
3
4
5
data = ['ACME', 50, 91.9, (2023, 9, 9)]
name, shares, price, data = data

print(name, data)

Output
1
ACME (2023, 9, 9)

1.2 从可迭代对象中分解元素

1
2
3
4
5
6
7
8
9
10
11
def avg(nums):
return sum(nums)/len(nums)


def drop_fst_and_lst(self):
fst, *mid, lst = self
return avg(mid)


grades = [100, 10, 10, 10, 10, 10, 0]
print(drop_fst_and_lst(grades))
Output
1
10.0

Tips:

将函数传入值改为self可避免暴露函数内的变量名。

1
2
3
4
5
6
7
line = 'gting:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'

unmae, *fields, homedir, sh = line.split(':')

print(unmae)
print(homedir)
print(sh)
Output
1
2
3
gting
/var/empty
/usr/bin/false

1.3 双向队列

初始化:q = deque(maxlen=?)

q.append(?) 右侧插入元素

q.appendleft(?) 左侧插入元素

q.pop() 弹出右侧元素

q.popleft() 弹出左侧元素

如果不指定队列的大小就是一个无限的队列,可在两段进行插入和弹出,并且都是O(1),而列表是O(n)

1.4 堆heapq

找到最大或者最小的N个元素。

imort heapq

heapq中有两个函数 nlargest()nsmallest()

heapq.nlargest(?, ?list, key) 取出最大的前三项,最小同理。

heapq.heapify(?list)将list排序为小顶堆

heapq.heappop() 获取弹出对顶元素,O(logn)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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}
]

cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])

print(cheap)
print(expensive)
Output
1
2
[{'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}]
[{'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'ACME', 'shares': 75, 'price': 115.65}, {'name': 'IBM', 'shares': 100, 'price': 91.1}]

1.5 优先队列

使用 heap实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# example.py
#
# Example of a priority queue

import heapq


class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0

def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1

def pop(self):
return heapq.heappop(self._queue)[-1]


# Example use
class Item:
def __init__(self, name):
self.name = name

def __repr__(self):
return 'Item({!r})'.format(self.name)


q = PriorityQueue()
q.push(Item('foo'), 1)
q.push(Item('bar'), 5)
q.push(Item('spam'), 4)
q.push(Item('grok'), 1)

print("Should be bar:", q.pop())
print("Should be spam:", q.pop())
print("Should be foo:", q.pop())
print("Should be grok:", q.pop())
Output
1
2
3
4
Should be bar: Item('bar')
Should be spam: Item('spam')
Should be foo: Item('foo')
Should be grok: Item('grok')

1.6 一键多值字典multdct

使用from collections import defaultdict

使用例:

1
2
3
4
5
6
7
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)

d2 = defaultdict(set)
d2['a'].add(1)
d2['a'].add(2)

1.7 有序字典

使用from collections import OrderedDict 会严格按照字典添加的顺序进行。

可在JSON编码中控制各字段的顺序。

1.8 字典中的计算