[英]How do I count the number of times each value appears for a key?
For example, if I have a dictionary that lists farm animals, it would be as follows: 例如,如果我有一本列出农场动物的字典,它将如下所示:
{"groupA":["cow","lamb","lamb","lamb"], "groupB":["cow","cow"]}
How would I be able to count the number of times each value appears for the corresponding key? 我如何计算对应键每个值出现的次数? I want groupA cow 1, groupA lamb 3, groupB cow 2. The even trickier part is that the dictionary is not fixed, it needs to be dynamic. 我想要groupA母牛1,groupA羔羊3,groupB母牛2。更棘手的部分是字典不是固定的,它需要动态。 There may be more keys that go on past groupB (ex. groupC, group D) and might have more or less values associated with it. 可能有更多键经过组B(例如,组C,组D),并且可能具有更多或更少的值。 I have figured out a static way by popping out each key then using the if function to see what it contains then put a counter to it. 我想出了一种静态方法,方法是弹出每个键,然后使用if函数查看其包含的内容,然后为其添加一个计数器。 (The only two animals will be either cow or lamb). (仅有的两只动物将是牛或羊)。 I unfortunately cannot determine how to do this dynamically because I will never know how many keys there will be. 不幸的是,我无法确定如何动态地执行此操作,因为我永远不知道会有多少个键。 Thank you guys so much for the help. 非常感谢你们的帮助。 I couldn't find the answer anywhere and am extremely frustrated at the moment. 我在任何地方都找不到答案,目前感到非常沮丧。
I think the canonical approach would be to use collections.Counter
: 我认为规范的方法是使用collections.Counter
:
>>> from collections import Counter
>>> d = {"groupA":["cow","lamb","lamb","lamb"], "groupB":["cow","cow"]}
>>> dc = {k: Counter(v) for k,v in d.items()}
>>> dc
{'groupA': Counter({'lamb': 3, 'cow': 1}), 'groupB': Counter({'cow': 2})}
after which you can access the nested counts: 之后,您可以访问嵌套计数:
>>> dc["groupA"]["lamb"]
3
Another iterpretation using Counter 使用Counter的另一种解释
>>> from collections import Counter
>>> D = {"groupA":["cow","lamb","lamb","lamb"], "groupB":["cow","cow"]}
>>> Counter((k,v) for k in D for v in D[k])
Counter({('groupA', 'lamb'): 3, ('groupB', 'cow'): 2, ('groupA', 'cow'): 1})
If you need a dict
: 如果你需要一个dict
:
>>> dict(Counter((k,v) for k in D for v in D[k]))
{('groupA', 'cow'): 1, ('groupB', 'cow'): 2, ('groupA', 'lamb'): 3}
or a list
: 或list
:
>>> list(Counter((k,v) for k in D for v in D[k]).items())
[(('groupA', 'cow'), 1), (('groupB', 'cow'), 2), (('groupA', 'lamb'), 3)]
You can first count the number of each item in a list with a function something like this: 您可以先使用类似以下功能的功能来计算列表中每个项目的数量:
def countList(list):
counts = {}
for l in list:
if l in counts:
counts[l] += 1
else:
counts[l] = 1
return counts
Use the count
method on each list of animals: 对每个动物列表使用count
方法:
farm = {"groupA":["cow","lamb","lamb","lamb"], "groupB":["cow","cow"]}
for group_name, animal_list in farm.items():
for animal in 'cow', 'lamb':
print(group_name, animal, animal_list.count(animal))
rite={"groupA":["cow","lamb","lamb","lamb"], "groupB":["cow","cow"]}
for i,j in rite.iteritems():
b=set(j)
for k in b:
print i,k,j.count(k)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.