collections模块


collections模块

  • collections模块内部提供了一些高阶的数据类型

1、具名元组namedtuple

# 1、具名元组(namedtuple)
from collections import namedtuple

'''
具名元组的表现形式
1、以列表的形式存放名字:
namedtuple('元组名',[名字1,名字2,...])
2、以字符串空格的形式存放名字:
namedtuple('元组名','名字1 名字2 ...')
'''
point = namedtuple('坐标', ['x', 'y'])
res = point(3, 4)
print(res)  # 坐标(x=3, y=4)
# 也可以通过点名字的方式取出其中某个元素
print(res.x)  # 3
print(res.y)  # 4
# 传值的个数和名字的个数相等
point = namedtuple('坐标', 'x y z')
res1 = point(3, 4, 5)
print(res1.x)  # 3
print(res1.y)  # 4
print(res1.z)  

2、队列

# 2、队列
'''
队列遵循先进先出的原则,且一端只能进,另一端只能出
'''
# 队列模块
import queue  # 内置模块:队列(FIFO)

# 初始化队列
q = queue.Queue()
# 往队列中添加元素
q.put('1')
q.put('2')
q.put('3')
q.put('4')
# 从队列中取元素
a = q.get()
print(a)  # 1
q.get()
q.get()
q.get()
q.get()  # 当值取没了就会原地等待

3、双端队列

# 3、双端队列
'''
所谓的双端队列,同样也遵循先进先出的原则,但是双端队列的两端都可以进出
关键字:deque
'''
from collections import deque

q = deque([1, 2, 3, 4, 5])
q.append(44)  # 从右边追加
q.appendleft(55)  # 从左边添加
# print(q)  # deque([55, 1, 2, 3, 4, 5, 44])
print(q.pop())  # 44 从右边开始弹出
print(q.popleft())

4、有序字典

# 4、有序字典
'''
我们一般的字典都是无序的,且在增加值的时候值也是无序,
但是collections自带的有序的字典会根据填值的顺序排好顺序,也就是有序字典
关键字:OrderedDict
'''
from collections import OrderedDict

order_dict = OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
print(order_dict)  # OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
order_dict['xxx'] = 111
print(order_dict)  # OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study'), ('xxx', 111)])

5、默认值字典

# 5、默认值字典
'''
关键字:defaultdict
'''
from collections import defaultdict

values = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
my_dict = defaultdict(list)
for value in values:
    if value > 60:
        my_dict['k1'].append(value)
    else:
        my_dict['k2'].append(value)
print(my_dict)

6、计数器

# 6、计数器
res = 'abcdeabcdabcaba'
# 统计字符串中每个元素出现的次数
# 1、传统方式:
new_dict = {}
for i in res:
    if i not in new_dict:
        new_dict[i] = 1
    else:
        new_dict[i] += 1
print(new_dict)
# 2、使用collections模块中的计数器
from collections import Counter  # 计数器
ret = Counter(res)
print(ret)

相关