python 数据结构

python中collections系列是对字典、元祖等数据结构的补充,不是python内置的,在使用之前,需要用 import collections 导入。

在collections系列中主要有以下内容:

 1. Counter(seq)  

    Counter()继承了dict类,其中seq为可迭代对象。接收seq,并以字典形式返回seq中每个元素(hashable)出现的次数。

 1 import collections
 2 
 3 s = 'abcdedcbae'
 4 l = ['a','b','c','d','x','y','b','d',]
 5 l1 = ['a','b','c','d','x','y',['b','d'],]    #不可以,list不可hash
 6 se = {1,'admin',2,3,5,6,'b','root','python'}
 7 t = (1,2,3,4,'a','root')
 8 d = {'name':'root','job':'python',}    #感觉无意义,返回的obj还是跟d一样的
 9 
10 obj = collections.Counter(l)
11 print(obj)
12 >>> Counter({'b': 2, 'd': 2, 'a': 1, 'c': 1, 'x': 1, 'y': 1})

  1.1  most_common(n)   传递一个值n,打印Counter()产生对象的前n个键值对,以列表存储

1 obj = Counter({'b': 2, 'd': 2, 'a': 1, 'c': 1, 'x': 1, 'y': 1})
2 obj1 = obj.most_common(3)
3 print(obj1)
4 >>>[('b', 2), ('d', 2), ('a', 1)]

  1.2  elements()  获取Counter()生成对象的所有键名,重复的几个会全部打印

obj = Counter({'b': 2, 'd': 2, 'a': 1, 'c': 1, 'x': 1, 'y': 1})
obj2 = obj.elements()    #返回一个迭代器
print(obj2)
>>> <itertools.chain object at 0x0000018CCD5EB4E0>
print(list(obj2))
>>> ['a', 'b', 'b', 'c', 'd', 'd', 'x', 'y']

  1.3 update(x)  更新计数器,把x的内容加到原来计数器中

 1 >>> import collections
 2 >>> 
 3 >>> s = 'abcd'
 4 >>> obj = collections.Counter(s)
 5 >>> obj
 6 Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1})     
 7 >>> obj.update('aab')
 8 >>> obj
 9 Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})       #可以更新字符串
10 >>> obj.update(['c','e',110,])
11 >>> obj
12 Counter({'a': 3, 'b': 2, 'c': 2, 'd': 1, 'e': 1, 110: 1})    #可以更新列表
13 >>> obj.update((110,2,'d'))
14 >>> obj
15 Counter({'a': 3, 'b': 2, 'c': 2, 'd': 2, 110: 2, 'e': 1, 2: 1})   #可以更新元组
16 >>> obj.update({'b','c',2,})
17 >>> obj
18 Counter({'a': 3, 'b': 3, 'c': 3, 'd': 2, 110: 2, 2: 2, 'e': 1})      #可以更新集合
19 >>> obj.update({'name':'root','a':'v',})
20 Traceback (most recent call last):
21   File "<pyshell#78>", line 1, in <module>                     #不能更新字典
22     obj.update({'name':'root','a':'v',})                       
23   File "C:Program FilesPython36libcollections\__init__.py", line 617, in update
24     self[elem] = count + self_get(elem, 0)
25 TypeError: must be str, not int
26 >>> obj.update(110)                      
27 Traceback (most recent call last):
28   File "<pyshell#79>", line 1, in <module>                #不能更新纯数字
29     obj.update(110)
30   File "C:Program FilesPython36libcollections\__init__.py", line 621, in update
31     _count_elements(self, iterable)
32 TypeError: 'int' object is not iterable
33 >>> 

  1.4 subtract(obj1)  接收一个参数,减少指定项,默认减少1(通过字典形式指定一次减少个数),不存在的就减为-1,依次减。作用与update()相反

 1 >>> obj
 2 Counter({'a': 3, 'b': 3, 'c': 3, 'd': 2, 110: 2, 2: 2, 'e': 1})
 3 
 4 >>> obj.subtract('a')
 5 >>> obj
 6 Counter({'b': 3, 'c': 3, 'a': 2, 'd': 2, 110: 2, 2: 2, 'e': 1})
 7 
 8 >>> obj.subtract(['a','b',110,])
 9 >>> obj
10 Counter({'c': 3, 'b': 2, 'd': 2, 2: 2, 'a': 1, 'e': 1, 110: 1})
11 
12 >>> obj.subtract(('c','e',110,))
13 >>> obj
14 Counter({'b': 2, 'c': 2, 'd': 2, 2: 2, 'a': 1, 'e': 0, 110: 0})
15 
16 >>> obj.subtract({'b':3,'d':2,110:2,})
17 >>> obj
18 Counter({'c': 2, 2: 2, 'a': 1, 'd': 0, 'e': 0, 'b': -1, 110: -2})
19 
20 >>> obj.subtract({'m':2,5:1,})
21 >>> obj
22 Counter({'c': 2, 2: 2, 'a': 1, 'd': 0, 'e': 0, 'b': -1, 5: -1, 110: -2, 'm': -2})
23 >>> 

  2. OrderedDict()

    有序字典继承dict类。有点类似循环一个顺序列表,再由list的每个位置确定字典里面的键值对。记录字典添加键值对的先后顺序。

 1 >>> 
 2 >>> import collections
 3 >>> 
 4 >>> dic = collections.OrderedDict()   #定义一个有序字典
 5 >>> dic
 6 OrderedDict()
 7 >>> dic.update({'name':'root','job':'python',})
 8 >>> dic
 9 OrderedDict([('name', 'root'), ('job', 'python')])
10 >>> dic['age'] = 22
11 >>> dic
12 OrderedDict([('name', 'root'), ('job', 'python'), ('age', 22)])
13 >>> 

    2.1 move_to_end()  传递一个键名,将该键值对移动到最后

1 >>> dic 
2 OrderedDict([('name', 'root'), ('job', 'python'), ('age', 22)])
3 >>> dic.move_to_end('job')
4 >>> dic
5 OrderedDict([('name', 'root'), ('age', 22), ('job', 'python')])
6 >>> 

    2.2 popitem()  删除并获取排在最后的键值对。类似于堆栈(后进先出)。

>>> dic
OrderedDict([('name', 'root'), ('age', 22), ('job', 'python')])
>>> dic.popitem()
('job', 'python')
>>> dic
OrderedDict([('name', 'root'), ('age', 22)])
>>> 

    2.3 pop(k)  传递一个指定的键名k,删除对应键值对,并获取值。

1 >>> dic
2 OrderedDict([('name', 'root'), ('age', 22), ('gender', 'man')])
3 >>> dic.pop('age')
4 22
5 >>> dic
6 OrderedDict([('name', 'root'), ('gender', 'man')])
7 >>> 

  3. defaultdict()

    默认字典,继承于dict类。

 1 >>> 
 2 >>> import collections
 3 >>> 
 4 >>> dic = collections.defaultdict(list)    #创建一个默认值为列表的字典,任意键名在未直接赋值为不可变类型时,都可以直接使用列表的方法。
 5 >>> dic
 6 defaultdict(<class 'list'>, {})
 7 >>> dic['name'].append('root')
 8 >>> dic['age'] = 22
 9 >>> dic
10 defaultdict(<class 'list'>, {'name': ['root'], 'age': 22})
11 >>> dic['age'].append(20)
12 Traceback (most recent call last):
13   File "<pyshell#127>", line 1, in <module>
14     dic['age'].append(20)
15 AttributeError: 'int' object has no attribute 'append'
16 >>> 

  4. namedtuple()

    可命名元组。给元组里面的每个值取个名字。

 1 >>> 
 2 >>> import collections
 3 >>> 
 4 >>> MytupleClass = collections.namedtuple('MytupleClass',['x','y','z'])     #可命名元组是先自定义一个类,由类实例化一个可命名元祖对象
 5 >>> 
 6 >>> obj = MytupleClass(11,22,33)       #实例化可命名元组,创建一个
 7 >>> obj.x
 8 11
 9 >>> obj.y
10 22
11 >>> obj.z
12 33
13 >>> obj
14 >>> MytupleClass(x=11,y=22,z=33)
15 >>>

  5. deque()

    deque (循环队列)。取数据默认从右边取。

>>> import collections
>>> 
>>> de = collections.deque()     #定义一个双向队列(循环队列)
>>>

    双向队列的方法:

append(self)
'''往双向队列右边加入一个元素'''
     
appendleft(self)
'''往双向队列左边加入一个元素'''
     
clear(self)
'''清空双向队列中的所有元素'''     

count(self, value)
'''返回指定元素在双向队列中的个数'''

extend(self)
'''用一个迭代器从右边扩展双向队列'''
     
insert(index,value)
'''向双向队列中指定位置插入一个元素'''

extendleft(self)
'''用一个迭代器从左边扩展双向队列(与从后面插入方向相反,类是于一个一个的放进去的)''' 

index(value)
'''返回从左到右遇到的第一个value的索引'''

copy()
'''浅复制双向队列'''

pop(self)
'''删除并返回最右边的一个元素'''
     
popleft(self)
'''删除并返回最左边的一个元素'''  

remove(self, value)
'''删除第一次出现的值'''

reverse(self)
'''反转双向队列'''

rotate(n)
'''循环队列(双向队列)向右旋转双向队列n步(默认n = 1)。如果n是负的,就向左旋转'''    

  

  补充:

  说了collections系列中的双向队列,接下来讲讲 queue 模块中的单向队列:

1 >>> import queue         #单向队列 Queue 在 queue 模块中
2 >>> 
3 >>> q = queue.Queue()
4 >>> type(q)
5 <class 'queue.Queue'>
6 >>> 

 单向队列中的部分函数

1 put()
2 '''传递一个参数,向单向队列里面插入数据'''
3 
4 get()
5 '''从单向队列中取出数据,不支持传参(先进先出),依次取出,每次一个'''
6 
7 qsize()
8 '''单向队列中元素的个数'''

未完待续。。。

原文地址:https://www.cnblogs.com/xtsec/p/6607663.html