数据结构与算法篇——python内置数据结构模块

heapq:
1、构造最小堆
heapq.heapify(list),将x转化为heap
heapq.heappush(heap,item),插入item至list中
heapq.heappushpop(heap,item),插入item,并返回最小值
heapq.heapreplace(heap,item),先返回最小值,再插入item
heapq.merge(list1,list2)合并iterables并排序

2、索引
最小值索引:heap[0]
pop最小值:heapq.heappop(heap)
返回n个最大值:heapq.nlargest(n,iterable) 等于sorted(iterable,key,reverse=True)[:n]
返回n个最小值:heapq.nsmallest(n,iterable)等于sorted(iterable,key)[:n]
bisect:
1、搜索#返回索引位置
bisect.bisect(sorted list,item)==bisect.bisect_left(sorted list,item)
bisect.bisect_right(sorted list,item)
2、插入#无返回值,对list操作
bisect.insort(sorted list,item)==bisect.insort_left(sorted list,item)
bisect.insort_right()

import bisect
a=[1,2,3]
bisect.insort(a,1)#无返回值,对a插入1
a
=>[1,1,2,3]

collections常用数据类型
1、deque
a=collections.deque(iterable)#定义deque类实例

a.append(x)
a.appendleft(x)
a.extend(iterable)
a.extendleft(iterable)
a.insert(index,x)
a.pop()
a.popleft()
a.remove(x)

a.index(x)
a.count(x)

a.coupy()
a.clear()
a.reverse()
a.rotate(n=1)==a.append(a.popleft())
2、defaultdict
d=defaultdict(list set or int)#定义dict,其中list int为value的类型
int时默认为0,list默认为空
d[key]=value
d.setdefault(key,value)
3、Counter
c=Counter(iterable)#返回Counter({‘blue’: 3, ‘red’: 2, ‘green’: 1})
c[key]返回key的次数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值