collections模块
1.namedtuple(具名元组)
from collections import namedtuple
'''
namedtuple('名称',[名字1,名字2,....])
res = namedtuple('名称,'名字1 名字2 ...')
res1 = res('值1','值2')
print(res1) # 结果为: 名称(名字1='值1',名字2='值2')
print(res1.名字1) # 结果为 : 值1
'''
point = namedtuple('坐标',['x','y'])
res = point('11','22')
print(res)
print(res.x)
print(res.y)
point = namedtuple('坐标', 'x y z')
res = point(11, 22, 33)
print(res)
card = namedtuple('扑克','花色 点数')
card1 = card('♦','A')
print(card1)
print(card1.花色)

- 队列
队列模式
import queue
q = queue.Queue()
q.put('first')
q.put('second')
q.put('third')
print(q.get())
print(q.get())
print(q.get())
- 双端队列
from collections import deque
q=deque([11,22,33])
q.append(44)
q.appendleft(55)
print(q.pop())
print(q.popleft())

- 有序字典
order_dict = dict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
print(order_dict)
{'hobby': 'study', 'pwd': 123, 'name': 'jason'}
from collections import OrderedDict
normal_dict = OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
print(normal_dict)
normal_dict['xxx'] = 1111
print(normal_dict)
order_dict = dict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
print(order_dict)
order_dict['ttt'] = 2222
- 默认值字典
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 = 'abcdeackjisdhvnvnvnvnbbvcccc'
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)
Counter({'c': 6, 'v': 5, 'n': 4, 'b': 3, 'a': 2, 'd': 2, 'e': 1, 'k': 1, 'j': 1, 'i': 1, 's': 1, 'h': 1})
ret =Counter(['the', 'foo', 'the', 'foo', 'the', 'defenestration', 'the'])
print(ret)
Counter({'the': 4, 'foo': 2, 'defenestration': 1})

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)