列表列表中Python的项目数 [英] Python count of items in a dictionary of lists

查看:112
本文介绍了列表列表中Python的项目数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,我想为某个列表添加一个值...
我有以下列表字典。

I have a dictionary of lists for which I want to add a value to a particular list... I have the following dictionary of lists.

d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill' 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']}

我想基本上排除名字的数量并返回。所以在这个例如:

I want to essentially count out the number of names and return in. So in this case it would be something like

Adam: 2
Bill: 2
John: 1
Bob: 1
Joe: 1

为了使事情变得更容易,所有的名字都是第二个元素在列表中或

To make things easier, all names are the second element in the list or

for i in d:
     d[i][1]

任何想法如何有效地执行此操作?我现在只是手动检查每个名字并计数并返回= =

Any idea how I can do this efficiently? I'm currently just manually checking for each name and counting and returning that =/

提前感谢!

推荐答案

collections.Counter 总是有益于计数。

collections.Counter is always good for counting things.

>>> from collections import Counter
>>> d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill', 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']}
>>> # create a list of only the values you want to count,
>>> # and pass to Counter()
>>> c = Counter([values[1] for values in d.itervalues()])
>>> c
Counter({'Adam': 2, 'Bill': 2, 'Bob': 1, 'John': 1, 'Joe': 1})

这篇关于列表列表中Python的项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆