开发者

Count the multiple occurrences in a set

if group not in g:
    g[group] = set()
g[group].add(name)

goes through a list of groups with this structure:

Group: 开发者_如何学GoA
Name: Bob

and adds to the set the names of persons belonging to a specific group. The names in the set are unique and we don't know how many similar names there are in a group. So e.g. if there are two 'Bob' names or 5 'Mike' names, how can I count the multiple occurrences of the names as well to have something like this:

Group A: Bob 2, Mike 5
Group B: Jane 4

and so on. Thanks in advance.


Looks like you might be better off with a Counter:

>>> from collections import Counter
>>> mylist = ["Bob", "Mike", "Bob", "Mike", "Mike", "Mike", "Bob"]
>>> Counter(mylist)
Counter({'Mike': 4, 'Bob': 3})


use a dict of dicts to count, e.g. as follows:

tralala = dict()

for group, name in [('A', 'Bob'), ('B', 'Jane'), ('A', 'Bob')]:
    tralala.setdefault(group, dict()).setdefault(name, 0) 
    tralala[group][name] += 1

print tralala

This results in

{'A': {'Bob': 2}, 'B': {'Jane': 1}}



from collections import Counter, defaultdict

lst = [('B', 'Bob'), ('A', 'Andy'), ('C', 'Charles'), ('A', 'Adam'), ('B', 'Abraham')]

# assumes people can appear in more than one group def groups(lst): counter = Counter(lst) result = defaultdict(dict) for (group, name), value in counter.iteritems(): result[group][name] = value return result

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜