随笔- 310  文章- 1  评论- 0  阅读- 86066 

Counter:字典的子类,提供了可哈希对象的计数功能
defaultdict:字典的子类,提供了一个工厂函数,为字典查询提供了默认值
OrderedDict:字典的子类,保留了他们被添加的顺序
namedtuple:创建命名元组子类的工厂函数
deque:类似列表容器,实现了在两端快速添加(append)和弹出(pop)
ChainMap:类似字典的容器类,将多个映射集合到一个视图里面

 

复制代码
import  collections

# *****[Counter]*****

# 统计字符出现的次数
ret = collections.Counter('very good')
print(ret) #Counter({'o': 2, 'v': 1, 'e': 1, 'r': 1, 'y': 1, ' ': 1, 'g': 1, 'd': 1})
# 统计单词数
ret = collections.Counter('hello world python hello'.split())
print(ret) #Counter({'hello': 2, 'world': 1, 'python': 1})

# *****[defaultdict]*****
# 为字典的没有的key提供一个默认的值。参数应该是一个函数,当没有参数调用时返回默认值。如果没有传递任何内容,则默认为None
d = collections.defaultdict()
print(d) #defaultdict(None, {})
d = collections.defaultdict(int)
print(d) #defaultdict(<class 'int'>, {})
d['apple'] += 2
print(d) # defaultdict(<class 'int'>, {'apple': 2})
print(d['app']) # 0

# *****[OrderedDict]*****
o = collections.OrderedDict({"key1":"value1","key2":"value2","key3":"value3"})
print(o.get("key1")) # value1
print(o) # OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

# *****[OrderedDict]*****
Person = collections.namedtuple('Person', ['age', 'height', 'name'])
Human = collections.namedtuple('Human', 'age, height, name')

# 实例化命令元组
tom = Person(30,178,'Tom')
jack = Human(20,179,'Jack')
print(tom) #Person(age=30, height=178, name='Tom')
print(jack) #Human(age=20, height=179, name='Jack')
print(tom.age,tom.height,tom.name) #30 178 Tom
print(jack.age,jack.height,jack.name) #20 179 Jack

# *****[deque]*****
d=collections.deque(['a',1,3])
d.append("python")
print(d) #deque(['hello', 'a', 1, 3, 'python'])
d.appendleft("hello")
print(d) #deque(['a', 1, 3, 'python'])

# *****[ChainMap]*****
d1 = {'apple':1,'banana':2}
d2 = {'orange':2,'apple':3,'pike':1}
d3 = {'hello':2,'opp':3,'app':1}
chain = collections.ChainMap(d1,d2,d3)
print(chain) #ChainMap({'apple': 1, 'banana': 2}, {'orange': 2, 'apple': 3, 'pike': 1}, {'hello': 2, 'opp': 3, 'app': 1})
print(chain.get("hello")) #2
print(dict(chain)) #{'hello': 2, 'opp': 3, 'app': 1, 'orange': 2, 'apple': 1, 'pike': 1, 'banana': 2}
复制代码

 

 posted on   boye169  阅读(32)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示