image.png
collections模块
namedtuple 让tuple属性可读
Point = collections.namedtuple('Point','x,y,z')
p = Point(1,2,3)
print(p.x)
print(p[1])
print(p.z)
deque 双端队列
de = collections.deque()
de.append(6)
de.appendleft(3)
de.appendleft(5)
print(de.popleft())
print(de)
Counter 需要计数器的地方使用Counter
c =collections.Counter('hello,world,你好,python, collections.test')
# for i in c.items():
# print(i)
print(c)
print(c.most_common())
print(c.pop('l'))
print(c.most_common())
OrderedDict有序字典,可以用于实现 LRUcache
od = collections.OrderedDict()
od['v'] = 'v'
od['a'] = 'a'
od['z'] = 'z'
od.move_to_end('a')
print(list(od.keys()))
defaultdict 有默认值的字典
dd = collections.defaultdict(int)
dd['a']
dd['b']+=1
print(dd)
什么是LRUCache
Least-Recently-Used 替换掉最近最少使用的对象
缓存剔除策略, 当缓存空间不够用的时候需要一种方式剔除key
常用的有LRU, LFU等
LRU通过使用一个循环双端队列不断把最新访问的key放到表头实现
LRUCache 实现
class LRUCache:
def __init__(self, most=5):
self.od = collections.OrderedDict()
self.most = most
def get(self, key):
if key in self.od:
val = self.od[key]
self.od.move_to_end(key)
return val
else:
return -1
def put(self, key, value):
if key in self.od:
del self.od[key]
self.od[key] = value
else:
self.od[key] = value
if len(self.od) > self.most:
self.od.popitem(last=False)
l = LRUCache()
keys = ['a', 'b', 'c', 'd', 'e', 'f']
for key in keys:
l.put(key, key)
l.get('d')
print(l.od)
list 和 tuple 区别
都是线性结构, 支持下标访问
list是可变对象, tuple保存的引用不可变,
保存的引用不可变是指你没法替换掉这个对象,但是如果这个对象本身是一个可变对象,是可以修改这个引用指向的可变对象的
t = ([1], 2, 3)
t[0].append(4)
print(t)
list 没法作为字典的key, tuple可以,(可变对象不可hash,key必须是可hash的,因为一直在变,hash值也一直在变)
排序
快速排序
"""
遍历列表,第一个值与其他值进行判断,如果小于该值放到左侧列表中,大于该值放到右侧列表中,然后将生成的两个列表分别调用该函数,重复此动作,
直至列表中只剩下一个值,将该值返回,最后组合成列表
"""
def my_sort(array):
if len(array) < 2:
return array
else:
po = array[0]
left = [i for i in array[1:] if i <= po]
right = [i for i in array[1:] if i > po]
return my_sort(left) + [po] + my_sort(right)
list1 = [2, 3,85,86,12,874,125,358,71,9, 4, 1]
list2 = my_sort(list1)
print(list2)
归并排序
# 将两个有序列表排序,然后进行归并排序
def merge_sorted_list(list_a, list_b):
len_a, len_b = len(list_a), len(list_b)
a = b = 0
final_list = []
while a < len_a and b < len_b:
if list_a[a] < list_b[b]:
final_list.append(list_a[a])
a += 1
else:
final_list.append(list_b[b])
b += 1
if a < len_a:
final_list.extend(list_a[a:])
else:
final_list.extend(list_b[b:])
return final_list
a = [0, 2, 5, 8]
b = [3, 5, 8, 20, ]
print(merge_sorted_list(a, b))
# 归并排序
def mergesort(array):
# 递归出口
if len(array) <= 1:
return array
else:
mid = int(len(array) / 2)
left = mergesort(array[:mid])
right = mergesort(array[mid:])
return merge_sorted_list(left, right)
a = [0, 2, 1,5, 8, 9,4,80,21]
print(mergesort(a))
堆排序
# 堆排序
def heapsort_use_heapq(iterable):
from heapq import heappush, heappop
items = []
for value in iterable:
heappush(items, value)
return [heappop(items) for i in range(len(items))]
array = [2, 1, 3, 8, 4, 5, 8, 7, 2, 1, 8, 6, 2]
list2 = heapsort_use_heapq(array)
print(list2)
二分查找
# 二分查找
def binary_search(sorted_array, val):
if not sorted_array:
return -1
beg = 0
end = len(sorted_array) - 1
while beg <= end:
mid = int((beg + end) / 2)
if sorted_array[mid] == val:
return mid
if sorted_array[mid] < val:
beg = mid + 1
else:
end = mid - 1
return -1
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
val = 6
print(binary_search(list1, val))