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

如何统计Python列表中每个name键对应值的出现次数

统计Python列表中name字段的出现次数

最简洁方案:使用collections.Counter

Counter是Python标准库中专门用于统计频次的工具,直接提取所有name值传入即可完成统计:

from collections import Counter

list1 = [
    {'state': 'active', 'name': 'Name1'},
    {'state': 'active', 'name': 'Name2'},
    {'state': 'inactive', 'name': 'Name3'},
    {'state': 'active', 'name': 'Name2'},
    {'state': 'active', 'name': 'Name1'},
    {'state': 'inactive', 'name': 'Name3'},
    {'state': 'inactive', 'name': 'Name4'},
    {'state': 'active', 'name': 'Name1'},
    {'state': 'inactive', 'name': 'Name2'},
]

# 生成name频次统计字典
name_counts = Counter(item['name'] for item in list1)

# 按预期格式输出结果
for name, count in name_counts.items():
    print(f"{count} counts for {name}")

运行输出:

3 counts for Name1
3 counts for Name2
2 counts for Name3
1 counts for Name4

灵活方案:使用defaultdict(int)

如果需要更灵活的计数逻辑,用defaultdict(int)直接累加计数比存列表更高效:

from collections import defaultdict

list1 = [
    {'state': 'active', 'name': 'Name1'},
    {'state': 'active', 'name': 'Name2'},
    {'state': 'inactive', 'name': 'Name3'},
    {'state': 'active', 'name': 'Name2'},
    {'state': 'active', 'name': 'Name1'},
    {'state': 'inactive', 'name': 'Name3'},
    {'state': 'inactive', 'name': 'Name4'},
    {'state': 'active', 'name': 'Name1'},
    {'state': 'inactive', 'name': 'Name2'},
]

count_dict = defaultdict(int)
for item in list1:
    count_dict[item['name']] += 1  # 每遇到一个name,计数加1

# 输出统计结果
for name, count in count_dict.items():
    print(f"{count} counts for {name}")

修复你现有代码的问题

你之前的sum(x)失败是因为x是字典的key(字符串类型),sum无法直接对字符串求和。如果要保留defaultdict(list)的写法,只需统计每个列表的长度即可:

from collections import defaultdict

list1 = [
    {'state': 'active', 'name': 'Name1'},
    {'state': 'active', 'name': 'Name2'},
    {'state': 'inactive', 'name': 'Name3'},
    {'state': 'active', 'name': 'Name2'},
    {'state': 'active', 'name': 'Name1'},
    {'state': 'inactive', 'name': 'Name3'},
    {'state': 'inactive', 'name': 'Name4'},
    {'state': 'active', 'name': 'Name1'},
    {'state': 'inactive', 'name': 'Name2'},
]

list2 = defaultdict(list)
for i in list1:
    list2[i['name']].append(i['name'])

# 遍历字典,取每个列表的长度作为出现次数
for name, name_list in list2.items():
    print(f"{len(name_list)} counts for {name}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 07:19:59