失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > python collection 和 heapq 模块使用说明

python collection 和 heapq 模块使用说明

时间:2019-04-24 04:13:18

相关推荐

python  collection  和  heapq  模块使用说明

一 :集合库collection

python 拥有一些内置的数据类型,collections模块提供啦几个额外的数据类型:

1,namedtuple 生成可以使用名字来访问元素内容的tuple子类

2,deque 双端队列,可以加速从另一侧追加和推出对象

3,counter 计数器,主要用来计数

4,orderedDict 有序字典

5,defaultdict 带有默认值的字典

1) namedtuple 命名的元祖形式,一般需要知道元祖里面每个字段代表什么含义,可以用命名元祖namedtuple

继承命名的tuples

2)deque 双端队列

deque最大的好处就是实现了从队列 头部快速增加和取出对象,比如popleft() 和appendleft()

append() appendleft() pop() popleft() extend() extendleft() rotate()

1,使用最多的就是限制队列长度,来获取队列的最后一个值或者几个值

2) deque 的其他用法,可以参考下

3) Counter 计数器

elements 返回一个迭代器,显示重复次数的元素,如果次数小于1,则被忽略

most_common 获取出现次数最多的元素

subtract 两个元素counter的元素进行相减

4) ordereddict 有序字典

5)defaultdict 默认字典

二 : heapd 堆队列

heapq.heappush(heap, item)

Push the value item onto the heap, maintaining the heap invariant.

heapq.heappop(heap)

Pop and return the smallest item from the heap, maintaining the heapinvariant. If the heap is empty,IndexErroris raised. To access thesmallest item without popping it, use heap[0].

heapq.heappushpop(heap, item)

Push item on the heap, thenpop and return the smallest item from the heap. The combined action runs more efficiently than heappush()followed by a separate call to heappop().

heapq.nlargest(n, iterable, key=None)

Return a list with the n largest elements from the dataset defined byiterable. key, if provided, specifies a function of one argument that isused to extract a comparison key from each element in the iterable:key=str.lower Equivalent to: sorted(iterable, key=key,reverse=True)[:n]

heapq.nsmallest(n, iterable, key=None)

Return a list with the n smallest elements from the dataset defined byiterable. key, if provided, specifies a function of one argument that isused to extract a comparison key from each element in the iterable:key=str.lower Equivalent to: sorted(iterable, key=key)[:n]

如果觉得《python collection 和 heapq 模块使用说明》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。