实现说明
for region, product, amount in sales 是唯一的迭代点——其余代码顺序执行一遍。
各个操作都建立在顶层绑定之上:sales、totals、failures。
使用要点
- 演示输出是带标签的(
apac as plain dict:、failed products by region:),每个操作都会留下自己的一行标注。
常见问题
需要安装第三方包吗?
不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。 全部导入都来自标准库:collections。 状态都挂在模块顶层:sales、totals、failures。
代码示例
from collections import defaultdict
# 工厂在首次访问时自动建值,分组不再需要 "键不存在" 的前置判断
sales = [
("emea", "subscriptions", 1200),
("apac", "services", 800),
("emea", "services", 450),
("apac", "subscriptions", 990),
]
totals = defaultdict(lambda: defaultdict(int))
for region, product, amount in sales:
totals[region][product] += amount
for region in sorted(totals):
for product, amount in sorted(totals[region].items()):
print(f"{region:5s} {product:14s} {amount}")
# defaultdict 就是 dict:需要普通字典时直接 dict() 转换
print("apac as plain dict:", dict(totals["apac"]))
# list 工厂按到达顺序收集成员:失败产品按 region 归组
failures = defaultdict(list)
for region, product, ok in [
("emea", "subscriptions", True),
("emea", "services", False),
("apac", "services", True),
]:
if not ok:
failures[region].append(product)
print("failed products by region:", dict(failures))