collections模块

collections模块

 

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

 

1.namedtuple(具名元组)

from collections import namedtuple

"""
namedtuple('名称',[名字1,名字2,...])
namedtuple('名称','名字1 名字2 ...')
"""
point = namedtuple('坐标', ['x', 'y'])
res = point(11, 22)
print(res)  # 坐标(x=11, y=22)
print(res.x)  # 11
print(res.y)  # 22
point = namedtuple('坐标', 'x y z')

res = point(11, 22, 33)
print(res)  # 坐标(x=11, y=22, z=33)
print(res.x)  # 11
print(res.y)  # 22
print(res.z)  # 33

card = namedtuple('扑克', '花色 点数')
card1 = card('', 'A')
card2 = card('', 'K')
print(card1)
print(card1.花色)
print(card1.点数)

 

2.queue(队列)

# 队列模块
import queue  # 内置队列模块:FIFO
# 初始化队列
q = queue.Queue()
# 往队列中添加元素
q.put('first')
q.put('second')
q.put('third')
# 从队列中获取元素
print(q.get())
print(q.get())
print(q.get())
print(q.get())  # 值去没了就会原地等待

 

3.deque(双端队列)

from collections import deque
q = deque([11,22,33])
q.append(44)  # 从右边添加
q.appendleft(55)  # 从左边添加
print(q.pop())  # 从右边取值
print(q.popleft())  # 从做边取值

 

4.OrderedDict(有序字典)

normal_dict = dict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
print(normal_dict)
{'hobby': 'study', 'pwd': 123, 'name': 'jason'}
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
order_dict
OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study'), ('xxx', 111)])
normal_dict['yyy'] = 222
normal_dict
{'hobby': 'study', 'pwd': 123, 'yyy': 222, 'name': 'jason'}

 

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.Counter(计数器)

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

 

 

END

 

posted @ 2021-11-25 21:16  Snails蜗牛  阅读(51)  评论(0编辑  收藏  举报