python之路(二)-collections系列

时间:2023-02-06 18:14:41

collections提供了一些比较方便的方法,使用时需要先导入模块

导入模块:

import collections

1. 计数器Counter

统计参数中出现的次数,以字典的方式返回结果,参数可以是字符串,列表,元祖等。

简单使用:
import collections
collections.Counter a = collections.Counter('aadfadfadfdfadfadfad')
print(a) #输出结果为:
Counter({'a': 7, 'd': 7, 'f': 6}) #统计一个字符串内每个字符出现的次数
b = collections.Counter(['abadfadfad','abc','abc','def',1243,121,121,124,124])
print(b)
#输出结果为: Counter({'abc': 2, 121: 2, 124: 2, 'abadfadfad': 1, 1243: 1, 'def': 1}) #统计一个列表内每个元素出现的次数
方法:字典有的方法它都有,并且还有自己独特的方法
__missing__
     """ 对于不存在的元素,返回计数器为0 """
'The count of elements not in the Counter is zero.'
# Needed so that self[missing_item] does not raise KeyError
return 0
示例:
import collections
b = collections.Counter(['abadfadfad','abc','abc','def',1243,121,121,124,124])
print(b)
c = b.__missing__('abc')
print(c)

most_common
  """ 按出现次数从大到小排序,列出低前n个,如果n超出总数范围,则列出所有元素 """
        '''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
示例:
import collections
b = collections.Counter(['abadfadfad','abc','abc','def',1243,121,121,124,124])
c = b.most_common(2) #打印出现次数最多的前两位
print(c) #输出结果:
[('abc', 2), (121, 2)] d = b.most_common(100) #100超出了结果范围,所以打印全部
print(d) #输出结果
[('abc', 2), (121, 2), (124, 2), ('abadfadfad', 1), (1243, 1), ('def', 1)]
 
  
elements
""" 计数器中的所有元素,注:此处非所有元素集合,而是包含所有元素集合的迭代器 """
'''Iterator over elements repeating each as many times as its count.
示例:
import collections
b = collections.Counter(['abadfadfad','abc','abc','def',1243,121,121,124,124])
c = b.elements() #所有元素,有重复的会重复打印
d = list(c)
print(d) #输出结果:
['abc', 'abc', 'abadfadfad', 121, 121, 1243, 124, 124, 'def']
update(self, iterable=None, **kwds):
""" 更新计数器,其实就是增加;如果原来没有,则新建,如果有则加一 """
'''Like dict.update() but add counts instead of replacing them.
示例:
import collections
b = collections.Counter(['abadfadfad','abc','abc','def',1243,121,121,124,124])
#update之前
print(b)
b.update(['abc'])
b.update([1111111111111111])
#update之后
print(b) #输出结果:
#update之前
Counter({'abc': 2, 121: 2, 124: 2, 'abadfadfad': 1, 1243: 1, 'def': 1}) #update之后
Counter({'abc': 3, 121: 2, 124: 2, 'abadfadfad': 1, 1111111111111111L: 1, 1243: 1, 'def': 1})

  
subtract(self, iterable=None, **kwds):
""" 相减,原来的计数器中的每一个元素的数量减去后添加的元素的数量 """
'''Like dict.update() but subtracts counts instead of replacing them.
Counts can be reduced below zero. Both the inputs and outputs are
allowed to contain zero and negative counts. 示例:
如果相减的元素之前不存在,相减之后他的值为-1
import collections
b = collections.Counter(['abadfadfad','abc','abc','def',1243,121,121,124,124])
print(b)
b.subtract(['def'])
b.subtract(['aaa'])
print(b) #输出结果:
#相减之前
Counter({'abc': 2, 121: 2, 124: 2, 'abadfadfad': 1, 1243: 1, 'def': 1}) #相减之后的结果:
Counter({'abc': 2, 121: 2, 124: 2, 'abadfadfad': 1, 1243: 1, 'def': 0, 'aaa': -1})
  
copy(self):
""" 拷贝 """
'Return a shallow copy.'
示例:
import collections
b = collections.Counter(['abadfadfad','abc','abc','def',1243,121,121,124,124])
print(b)
c = b.copy()
print(c) #输出结果:
Counter({'abc': 2, 121: 2, 124: 2, 'abadfadfad': 1, 1243: 1, 'def': 1})
Counter({'abc': 2, 121: 2, 124: 2, 'abadfadfad': 1, 1243: 1, 'def': 1})

2. 有序字典 OrderedDict

我们知道字典默认是无序的,如果我们在想使用有序的字典,那么就可以用collections的OrderedDic函数,可以得到一个有序的字典。

创建一个有序字典:
import collections
dic = collections.OrderedDict({'a':1,'b':2})
print(dic) #输出结果:
OrderedDict([('a', 1), ('b', 2)]) #无论执行多少次,这个结果的顺序永远不变
OrderedDict有序字典的创建原理其实就是python内部将key创建为一个列表,然后循环这个列表,去取对应的value值因为列表是有序的,所以读到的value也是有序的。

OrderedDict可以使用字典的所有方法,除此之外它还有自己特有的方法:
popitem 拿走最后一个元素,并return该元素的key和value,后进先出 类似内存的栈,
示例:
import collections
dic = collections.OrderedDict({'a':1,'b':2})
dic2 = dic.popitem()
#打印dic剩下的元素
print(dic)
#打印return得到的元素
print(dic2) #输出结果:
#剩下的语速
OrderedDict([('a', 1)]) #return得到的元素内容
('b', 2)
pop  拿走后返回值,参数为key,返回的值为value。如果参数不存在,会报错。
这个跟popitme的区别是popitem只能从最后一个元素删除,pop必须指定元素的key来删除,popitem返回的是key和value,pop返回的是vaule
示例:
import collections
dic = collections.OrderedDict({'a':1,'b':2})
dic2 = dic.pop('a')
print(dic)
print(dic2) #输出结果:
#pop后剩余的元素,此处返回的是key和value
OrderedDict([('b', 2)]) #pop返回的内容(返回的是一个vaule值)
1

setdefault 设置某一个k的默认值
与默认字典的区别,默认字典是给字典内所有的key设置了一个默认值,而setdefault是给某一个key设置了默认值。
import collections
dic = collections.OrderedDict({'a':1,'b':2}) dic.setdefault('c','Default')
print(dic) dic['c'] = 3
print(dic) #输出结果:
#给c设置了一个默认值Default
OrderedDict([('a', 1), ('b', 2), ('c', 'Default')]) #赋值之后c的值变成了3,而不是Default
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
update 如果k存在,修改为最新的值,如果不存在添加新的k和v

示例:
import collections
dic = collections.OrderedDict({'a':1,'b':2})
#b存在,执行了修改
dic.update({'b':100}) #c不存在,执行了添加
dic.update({'c':200}) print(dic) #输出结果:
OrderedDict([('a', 1), ('b', 100), ('c', 200)])

3.可命名元祖 namedtuple

自定义tuple,适用于类似坐标轴的场景,可以通过坐标轴取值,而不是下标取值

示例:

import collections
mytuples = collections.namedtuple('mytuples',['x','y','z'])
l2 = mytuples(1,2,3) #通过以下方法取x,y,z的值
print(l2.x)
print(l2.y)
print(l2.z)

4. 队列 deque

一个线程安全的双向队列

既然是双向队列,就是可以在任何位置写入和提取。

队列与栈的区别:

单向队列:先进先出

栈:后进先出

deque的常用方法:

append,appendletf(体现了双向队列的特性)

import collections
q1 = collections.deque(['a','b','c'])
q1.append('d')#默认往右侧追加
q1.appendleft([1])#往左侧追加
print(q1) #输出结果
deque([[1], 'a', 'b', 'c', 'd'])

clear 清空

import collections
q1 = collections.deque(['a','b','c'])
q1.clear()
print(q1) #输出结果:
deque([])

count 统计某个元素出现的次数

import collections
q1 = collections.deque(['a','b','c','a']) #统计a出现的次数
q2 = q1.count('a')
print(q2) #输出结果
2

extend extendleft 左右扩展(体现了双向队列特性)

import collections
q1 = collections.deque(['a','b','c','a'])
q2 = [1,2,3,4,5]
q3 = ['d','e','f']
q1.extend(q2) #默认在右侧扩展
q1.extendleft(q3)#在左侧扩展
print(q1) 输出结果:
deque(['f', 'e', 'd', 'a', 'b', 'c', 'a', 1, 2, 3, 4, 5])

pop 删除元素默认从右边删除,并返回删除的元素(体现了双向队列特性)

import collections
q1 = collections.deque(['a','b','c'])
q2 = q1.pop()
print(q1)
print(q2) #输出结果:
#删除了右侧的元素
deque(['a', 'b'])
#并返回了删除的元素
c

popleft 从左侧开始删除,并返回删除的元素(体现了双向队列特性)

import collections
q1 = collections.deque(['a','b','c'])
q2 = q1.popleft()
print(q1)
print(q2) #输出结果:
#删除了右侧的元素
deque(['b', 'c'])
#并返回了删除的元素
a

remove 删除某元素

import collections
q1 = collections.deque(['a','b','c'])
q1.remove('a')
print(q1) #输出结果:
deque(['b', 'c'])

revers 反转

import collections
q1 = collections.deque(['a','b','c'])
print(q1)
q1.reverse()
print(q1) #输出结果:
#反转前的结果
deque(['a', 'b', 'c'])
#反转后的结果
deque(['c', 'b', 'a'])

rotate 把后面的数据拿到第一位

相当于把元素连接成一个圆圈,依次把最后一位拿到第一位,其他元素顺势往后排。

import collections
q1 = collections.deque(['a','b','c'])
print(q1)
q1.rotate(2) #可以将元素旋转2次,或者更多次
print(q1) #输出结果:
#旋转前的结果
deque(['a', 'b', 'c'])
#旋转后的结果
deque(['b', 'c', 'a'])

5、 单向队列 queue.Queue 先进先出

常用方法:

定义队列:

import queue
q1 = queue.Queue(2) #这里的2是指队列里个元素个数

empty 如果队列是空的则打印True否则打印False

import queue
q1 = queue.Queue()
print(q1.empty()) #输出结果:
True
import queue
q1 = queue.Queue()
q1.put('a')
print(q1.empty())
#输出结果:
#此时队列不为空所以返回False False

full

前面说了可以在定义队列的时候确定队列内元素的个数,如果队列元素个数等于队列设置的个数则为True,反之则为False

示例:

import queue
q1 = queue.Queue(2)
q1.put('a')
q1.put('b')
print(q1.full()) #输出结果
True

get 取出队列中的元素,并返回删除的元素,类似于pop

示例:

import queue
q1 = queue.Queue()
q1.put('a') #先放进a
q1.put('b') #然后放进b
print(q1.qsize())
q2 = q1.get()
print(q1.qsize())
print(q2) #输出结果:
# 取出前队列的个数
2
#取出后队列的个数
1
#取出的队列元素,此处取出的是a
a
上例中,先进把a放进序列然后再把b放进序列,但是取出的时候是先取的a,这就说明了单向队列的特性:先进先出

put  将元素加入队列

qsize 统计元素的个数