python中的集合、堆和双端队列

集合、堆和双端队列

集合(set)

集合是一种元素排列顺序不确定的元素集。集合是可变的,因此集合不能作为dict中的键,并且由于集合智能包括不可变的值,因此集合中不能包括其他的集合。
集合中的常用函数

#生成一个集合
a = set(range(10))
print(a)

#集合中常用的方法
#union 表示求两个集合的并集,|也可以达到这个效果
b = {1,2,3,4}
c = {3,4,5,6}
print(c.union(b))
print(c|b)
#还有一些其他的方法和对应的运算符,比如&、-、^等,以下测试
print("b是不是c的子集"+str(b.issubset(c)))
print('b是不是b|c的子集'+str(b.issubset(b|c)))
print('b是不是c的超集'+str(b.issuperset(c)))
print('在b中且c中没有'+str(b.difference(c)))
print('在b中且c中没有'+str((b-c)))
print('在b中且c中没有以及在c中有b中没有'+str(b.symmetric_difference(c)))

输出结果:
E:\Anaconda3\python.exe D:/PyWorkspace/data_preprocess/venv/Test.py
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
b是不是c的子集False
b是不是b|c的子集True
b是不是c的超集False
在b中且c中没有{1, 2}
在b中且c中没有{1, 2}
在b中且c中没有以及在c中有b中没有{1, 2, 5, 6}

还有一种集合的类型是frozenset,就是不可变得集合,一般用于作为集合中的一个元素。

堆(heap)

堆是一种优先队列。在堆中可以以任何顺序添加对象,并且在任何时候找出并删除这个堆中最小的元素。在列表中有方法min可以达到相同的效果,但是堆的效率要高很多。Python中没有独立的堆类型,只有一些堆操作函数的模块(heapq),其中包含以下这些函数。

import heapq
from heapq import *
from random import shuffle

print([n for n in dir(heapq) if not n.startswith('_')])

data = list(range(10))
shuffle(data)
heap = []
for n in data:
    heappush(heap,n)
print(heap)
heappush(heap,0.5)
print(heap)

输出结果为:
E:\Anaconda3\python.exe D:/PyWorkspace/data_preprocess/venv/Test.py
[‘heapify’, ‘heappop’, ‘heappush’, ‘heappushpop’, ‘heapreplace’, ‘merge’, ‘nlargest’, ‘nsmallest’]
[0, 2, 1, 6, 5, 4, 3, 9, 7, 8]
[0, 0.5, 1, 6, 2, 4, 3, 9, 7, 8, 5]

双端队列

一般用于按照元素添加的顺序进行删除。最主要的类型是deque。
双端队列模型
基本操作
Deque() 创建一个空的双端队列
add_front(item) 从队头加入一个item元素
add_rear(item) 从队尾加入一个item元素
remove_front() 从队头删除一个item元素
remove_rear() 从队尾删除一个item元素
is_empty() 判断双端队列是否为空
size() 返回队列的大小

import collections
from collections import deque
print([n for n in dir(collections) if not n.startswith('_')])
# 实例化一个deque对象
d = deque()
# 和list的操作有些类似
d.append('a')
d.append('b')
d.append('c')
print(len(d))
print(d[0])
print(d[-1])
print(d)

运行结果:
E:\Anaconda3\python.exe D:/PyWorkspace/data_preprocess/venv/Test.py
[‘ChainMap’, ‘Counter’, ‘OrderedDict’, ‘UserDict’, ‘UserList’, ‘UserString’, ‘abc’, ‘defaultdict’, ‘deque’, ‘namedtuple’]
3
a
c
deque([‘a’, ‘b’, ‘c’])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值