collectinos模块,计数器

collections模块

namedtuple(具名元组)

from collections import namedtuple

# 基本格式
'''
  namedtuple('名称',[名字1,名字2,...])
  namedtuple('名称','名字1 名字2 ...')
'''
point = namedtuple('坐标', ['经度','纬度'])
res = point(121.213097, 31.219601)
print(res)
print(res.经度)
print(res.纬度)
'''
坐标(经度=121.213097, 纬度=31.219601)
121.213097
31.219601
'''
或者
from collections import namedtuple

point = namedtuple('坐标', '经度 纬度')
res = point(121.213097, 31.219601)
print(res)
print(res.经度)
print(res.纬度)
# namedtuple('坐标', '经度 纬度') 可以用空格方式,但是使用空格就不用添加列表

拓展操作
from collections import namedtuple

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

队列

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

双端队列

from collections import deque

q = deque([11, 22, 33, 44])
q.append(44) # 从右边添加
q.appendleft(99) # 从左边添加
print(q)
print(q.pop()) # 从右边取值
print(q.popleft()) # 从左边取值
'''
deque([99, 11, 22, 33, 44, 44])
44
99
'''

有序字典

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'}

默认字典

# ll = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
将大于60和小于60的数字分别放入一个字典中
new_dict = {'k1':[], 'k2':[]}
for i in ll:
    if i < 60:
        new_dict.get('k2').append(i)
    else:
        new_dict.get('k1').append(i)
print(new_dict)
# 使用默认字典的方式
	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)

计数器

res = 'abcabcabcabcabc'
new_dict = {}
for i in res:
    if i not in new_dict:
        new_dict[i] = 1
    else:
        new_dict[i] += 1

print(new_dict)

# {'a': 5, 'b': 5, 'c': 5}
# 使用计数器模块
from collections import Counter

res = 'abcabcabcabcabc'
ret = Counter(res)
print(ret)
# Counter({'a': 5, 'b': 5, 'c': 5})

溜了溜了

posted @ 2021-11-25 21:11  谢俊杰  阅读(32)  评论(0编辑  收藏  举报