You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从defaultdict(Counter)结果拆分出s1、s2各自的元素计数字典?

拆分Counter统计结果为独立字典

嗨,这事儿其实挺简单的,咱们基于你已经得到的defaultdict(Counter)结果来拆分就行~先回顾下你的基础数据和之前的实现:

原始数据与已有代码

你的原始嵌套列表数据:

sumlist = [ ['a01', '01-24-2017', 's1'], ['a03', '01-24-2017', 's2'], ['a03', '09-24-2017', 's1'], ['a03', '10-23-2017', 's1'], ['a04', '11-01-2017', 's1'], ['a04', '11-02-2017', 's2'], ['a04', '11-03-2017', 's1'], ['a04', '01-01-2017', 's1']]

通过defaultdict(Counter)完成的统计代码:

from collections import defaultdict, Counter

d = defaultdict(Counter)
for animal, date, station in sumlist:
    d[animal][station] += 1

拆分方法

方法1:字典推导式(简洁高效)

直接用字典推导式从d中提取对应s1和s2的次数,用get()方法避免因无对应键抛出KeyError:

# 提取各元素对应s1的出现次数
s1_counts = {animal: cnts.get('s1', 0) for animal, cnts in d.items()}
# 提取各元素对应s2的出现次数
s2_counts = {animal: cnts.get('s2', 0) for animal, cnts in d.items()}

执行后得到的结果(对应你提供的原始数据):

  • s1_counts → {'a01': 1, 'a03': 2, 'a04': 3}
  • s2_counts → {'a01': 0, 'a03': 1, 'a04': 1}

方法2:手动遍历构建(直观易懂)

如果觉得推导式不够直观,也可以用循环逐步构建字典,逻辑更清晰:

s1_counts = {}
s2_counts = {}

for animal, station_counter in d.items():
    # 给每个元素赋值s1的次数,无记录则默认0
    s1_counts[animal] = station_counter.get('s1', 0)
    # 同理处理s2的统计
    s2_counts[animal] = station_counter.get('s2', 0)

这个方法和推导式的结果完全一致,适合刚接触Python字典操作的朋友理解逻辑。

小贴士:使用get()而非直接通过键取值(比如station_counter['s1']),是为了处理某个元素从未出现过s1/s2的情况,避免抛出KeyError异常,让代码更健壮。

内容的提问来源于stack exchange,提问作者Code Vanessa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:59:02