use*_*318 7 python dictionary list
我有一个列表字典,我想为特定列表添加一个值...我有下面的列表字典.
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']}
Run Code Online (Sandbox Code Playgroud)
我想基本上计算出名字的数量并返回.所以在这种情况下它会是这样的
Adam: 2
Bill: 2
John: 1
Bob: 1
Joe: 1
Run Code Online (Sandbox Code Playgroud)
为了简化操作,所有名称都是列表中的第二个元素或
for i in d:
d[i][1]
Run Code Online (Sandbox Code Playgroud)
知道我怎么能有效地做到这一点?我目前只是手动检查每个名字并计算和返回= /
提前致谢!
mon*_*kut 17
collections.Counter 计算事物总是好的.
>>> 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})
Run Code Online (Sandbox Code Playgroud)