Python: Collections 模块

本文档属于学习 Python指南的一部分。您可以在此处查看完整指南:全面的 Python 指南

👋 欢迎来到 Stackhero 文档!

Stackhero 提供现成的 Python 云 解决方案,具有众多优势,包括:

  • 通过简单的 git push 在几秒钟内 部署您的应用程序。
  • 使用您自己的域名,并享受 HTTPS 证书的自动配置以增强安全性。
  • 享受 自动备份一键更新,以及简单、透明和可预测的定价,让您高枕无忧。
  • 通过私有和专用的 VM获得最佳的性能和强大的安全性

节省时间简化您的生活:只需 5 分钟即可试用 Stackhero 的 Python 云托管 解决方案!

collections 模块提供可以改进程序的专用容器数据类型。

from collections import namedtuple, defaultdict, Counter, deque

示例:

from collections import namedtuple, deque, Counter, OrderedDict, defaultdict

# namedtuple
Person = namedtuple('Person', 'name age')
person1 = Person("Alice", 30)
print(person1.name, person1.age)  # 输出:Alice 30

# deque
dq = deque([1, 2, 3, 4, 5])
dq.append(6)
dq.appendleft(0)
print(dq)  # 输出:deque([0, 1, 2, 3, 4, 5, 6])

# Counter
count = Counter("hello world")
print(count)  # 输出:Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

# OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
print(od)  # 输出:OrderedDict([('a', 1), ('b', 2), ('c', 3)])

# defaultdict
dd = defaultdict(int)
dd['a'] += 1
dd['b'] += 2
print(dd)  # 输出:defaultdict(<class 'int'>, {'a': 1, 'b': 2})