如何统计列表中每个键的值数量

-3 投票
3 回答
60 浏览
提问于 2025-04-12 20:51

我有一个这样的列表:

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 值有多少个。像这样:

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

这是我现在的代码:

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

我以为我可以用这个来统计(显然这是个完全失败的尝试):

for x in list2:
    sum(x)

我该怎么统计呢?

3 个回答

1

要计算你字典列表中每个名字出现的次数,可以使用collections模块里的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'},
]

name_counts = defaultdict(int)

for item in list1:
    name_counts[item['name']] += 1

for name, count in name_counts.items():
    print(f"{count} counts for {name}")
1

使用 Counter

from collections import Counter

counter = Counter(d['name'] for d in list1)
print(*counter.items())

# ('Name1', 3) ('Name2', 3) ('Name3', 2) ('Name4', 1)
1

好的,要做到这一点,你可以使用collections库中的counter。实现这个功能的代码大概会像下面这样:

counts = Counter(item['name'] for item in list1)
for name, count in counts.items():
    print(f"{count} counts for {name}")

撰写回答