python内建集合模块collections功能,计数,有序,双向队列

时间:2020-04-12
本文章向大家介绍python内建集合模块collections功能,计数,有序,双向队列,主要包括python内建集合模块collections功能,计数,有序,双向队列使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、官方介绍

这个模块实现了特定目标的容器,以提供Python标准内建容器 dict , list , set , 和 tuple 的替代选择。

namedtuple()

创建命名元组子类的工厂函数

deque

类似列表(list)的容器,实现了在两端快速添加(append)和弹出(pop)

ChainMap

类似字典(dict)的容器类,将多个映射集合到一个视图里面

Counter

字典的子类,提供了可哈希对象的计数功能

OrderedDict

字典的子类,保存了他们被添加的顺序

defaultdict

字典的子类,提供了一个工厂函数,为字典查询提供一个默认值

UserDict

封装了字典对象,简化了字典子类化

UserList

封装了列表对象,简化了列表子类化

UserString

封装了列表对象,简化了字符串子类化

官方文档:https://docs.python.org/zh-cn/3.8/library/collections.html#module-collections

下面只介绍几种

二、counter计数类

# 统计相同元素出现的次数,可以是列表,字符串
counter_test = collections.Counter(["name","age","weight","name"])
print(counter_test) #Counter({'name': 2, 'age': 1, 'weight': 1})

counter_test = collections.Counter("my name is maple")
print(counter_test) #Counter({'m': 3, ' ': 3, 'a': 2, 'e': 2, 'y': 1, 'n': 1, 'i': 1, 's': 1, 'p': 1, 'l': 1})

# 数量从大到小排列,获取前N个元素
print(counter_test.most_common(3)) #[('m', 3), (' ', 3), ('a', 2)]

# elements()取得计数器中的所有元素,获取的是一个可迭代对象
print(counter_test.elements()) #<itertools.chain object at 0x0000017422610160>
for i in counter_test.elements():
    print(i)

# subtract()相减,原来的计数器中的每一个元素的数量减去后添加的元素的数量
counter_test.subtract('hello')
print(counter_test) #Counter({'m': 3, ' ': 3, 'a': 2, 'y': 1, 'n': 1, 'e': 1, 'i': 1, 's': 1, 'p': 1, 'l': -1, 'h': -1, 'o': -1})

# update()更新计数器
counter_test.update('hello')
print(counter_test) #Counter({'m': 3, ' ': 3, 'a': 2, 'e': 2, 'y': 1, 'n': 1, 'i': 1, 's': 1, 'p': 1, 'l': 1, 'h': 0, 'o': 0})

三、有序字典orderedDict

from collections import OrderedDict
dic = OrderedDict()
dic['name'] = 'maple'
dic['age'] = '18'
dic['weight'] = '70'
print(dic) #OrderedDict([('name', 'maple'), ('age', '18'), ('weight', '70')])

# move_to_end('name') 移动指定的键值对到最后
dic.move_to_end("name")
print(dic) #OrderedDict([('age', '18'), ('weight', '70'), ('name', 'maple')])

# 其他方法与普通字典一样
print(dic.update({"heigh":"17"}))
print(dic.pop("age"))
print(dic.popitem())
print(dic.items())
print(dic.keys())
print(dic.values())

四、默认字典defaultdict

import collections
dic = collections.defaultdict(list)
dic['name'].append('maple')
print(dic)#defaultdict(<class 'list'>, {'name': ['maple']})

# defaultdict作用:元素分类
# 案例,将相同的数字放入同一个字典values列表中
# dic={"2":[2,2],"3":[3]...}
list1=[2,5,6,7,3,6,8,10,3,6,4,2]

dic={}
for i in list1:
    res=[]
    if str(i) in dic:
        dic[str(i)].append(i)
    else:
        res.append(i)
        dic[str(i)]=res
print(dic)#{'2': [2, 2], '5': [5], '6': [6, 6, 6], '7': [7], '3': [3, 3], '8': [8], '10': [10], '4': [4]}


dic=collections.defaultdict(list)
for i in list1:
    if str(i) in dic:
        dic[str(i)].append(i)
    else:
        dic[str(i)].append(i)
print(dic)#defaultdict(<class 'list'>, {'2': [2, 2], '5': [5], '6': [6, 6, 6], '7': [7], '3': [3, 3], '8': [8], '10': [10], '4': [4]})

五、双向队列deque

from collections import deque #创建双向队列
d = deque()
d.append('1')
d.append('2')

# append()向队列中插入数据(从右边插入)
d.append('3')
print(d)

# appendleft()向队列中插入数据(从左边插入)
d.appendleft('4')
print(d)

# clear()清空队列
d.clear()
print(d)

# count()计数
d.append('1')
d.append('1')
print(d)
print(d.count('1'))

# extend()从右边向队列添加额外元素
d.extend(['a','b','c'])
print(d)

# extendleft()从左边向队列添加元素
d.extendleft(['d','e','f'])
print(d)

# index()取得元素索引
d.index('1')

# insert()指定位置插入元素
d.insert(1,'z')
print(d)

# pop()从右边移除一个元素
d.pop()
print(d)

# popleft()从左边移除一个元素
d.popleft()
print(d)

# remove()移除指定元素
d.remove('1')
print(d)

# reverse()反转队列
d.reverse()
print(d)

# rotate()将右边指定的元素个数移到队列左边
d.append('4')
d.append('5')
d.append('6')
print(d)
d.rotate(3)
print(d)

原文地址:https://www.cnblogs.com/angelyan/p/12687607.html