Python强大的Collections模块中的deque工具---高级数据结构1

Collections是python中的一个功能强大的模块,它额外地提供了5种高级的数据结构,极大地提升程序运行的效率。这篇文章主要介绍Colletions中的deque工具,之后的文章中会详细地继续介绍其他四个工具。

1、Counter类(作为计数器) :这个是最常用的,是对字典类型的补充,用于统计元素出现的次数,具备字典的所有功能+计数的功能。

from collections import *
string = "abcdedgaabbccdd"
out = Counter(string)
print(out)

#输出:Counter({'d': 4, 'a': 3, 'b': 3, 'c': 3, 'e': 1, 'g': 1})

2、defaultdict类(默认字典):使用工厂函数创建字典,使用的时候不用考虑缺失key。在使用python原生的数据结构dict的时候,如果用d[key]这样的方式访问,当指定的key不存在时,是会抛出keyerror异常,但是,如果使用defaultdict,只要传入一个默认的工厂方法,那么请求一个不存在的key时,便会调用这个工厂方法使其结果来作为这个key的默认值。

from collections import defaultdict

dict1 = defaultdict(int)
dict2 = defaultdict(set)
dict3 = defaultdict(str)
dict4 = defaultdict(list)
dict1[2] ='two'

print(dict1[1])
print(dict2[1])
print(dict3[1])
print(dict4[1])


'''
返回结果如下:
0
set()

[]

'''

3、OrderedDict类(有序字典):dict中key是无序的,在做迭代时,无法确认key的顺序。ordereddict是对字典类型的补充,他记住了字典元素添加的顺序。


from collections import OrderedDict
od = OrderedDict([('a', 1), ('z', 2), ('c', 3)])
print (od)
d = dict([('a',1),('z',2),('c',3)])
print (d)


# 结果如下
print(od):   OrderedDict([('a', 1), ('z', 2), ('c', 3)])

print(d):    {'a': 1, 'c': 3, 'z': 2}

4、namedtuple类(可命名元组):tuple是一个不可变集合,namedtuple用来构建一个自定义的tuple对象,并且规定了tuple元素的个数,可通过属性而不是索引来引用tuple的某个元素,我们可以通过namedtuple很方便的自定义一个数据类型,它具有tuple的不变属性又可以根据属性来引用。 

from collections import namedtuple
point = namedtuple('point',['x','y'])
p = point(2,1)
print(p)
print("x=",p.x)
print("y=",p.y)

# 结果如下
x=2
y=1

isinstance(p,point)
True

isinstance(p,tuple)
True

5、deque类(双边队列):具有队列和栈的性质,在 list 的基础上增加了移动、旋转和增删等,它是以列表的形式组织,是一个非常好用的工具。它的基本操作如下:


相比于list实现的队列,deque实现拥有更低的时间和空间复杂度。list实现在出队(pop)和插入(insert)时的空间复杂度大约为O(n),deque在出队(pop)和入队(append)时的时间复杂度是O(1),所以总的来说deque更有优越性。

下面用几个简单的例子说明deque的用法:

1、支持in操作符:

q = collections.deque([1, 2, 3, 4])
print(5 in q)  # False
print(1 in q)  # True

        2、复制队列:

d=collections.deque([1])
d.append(2)
d.append(3)

d1=d.copy()
print(d1)

#输出:deque([1, 2, 3, 2, 3])

        3、顺时针或者逆时针旋转:

# 顺时针
q = collections.deque([1, 2, 3, 4])
q.rotate(1)
print(q)  # [4, 1, 2, 3]
q.rotate(1)
print(q)  # [3, 4, 1, 2]

# 逆时针
q = collections.deque([1, 2, 3, 4])
q.rotate(-1)
print(q)  # [2, 3, 4, 1]
q.rotate(-1)
print(q)  # [3, 4, 1, 2]

        4、其他操作:

#extend操作:
d=deque()
d.append(1)
d.extend([2,3,4])
print(d)

#输出:deque([1,2,3,4])

#extendleft操作:
d=deque()
d.append(1)
d.extendleft([2,3,4])
print(d)

#输出:deque([4,3,2,1])


#index 查找索引的位置:

deque(['a', 'b', 'c', 'd', 'e','f'])
print(d.index("c",0,4)) #指定查找的区间

#输出:2

#insert(位置,元素) 在指定的位置插入元素
#remove(元素值)   删除指定的元素
#reverse() 队列旋转

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值