How to count co-ocurrences with collections.Counter() in python?

大兔子大兔子 提交于 2019-12-05 02:09:34

问题


I learned about the collections.Counter() class recently and, as it's a neat (and fast??) way to count stuff, I started using it.

But I detected a bug on my program recently due to the fact that when I try to update the count with a tuple, it actually treats it as a sequence and updates the count for each item in the tuple instead of counting how many times I inserted that particular tuple.

For example, if you run:

import collections
counter = collections.Counter()
counter.update(('user1', 'loggedin'))
counter.update(('user2', 'compiled'))
counter.update(('user1', 'compiled'))

print counter

You'll get:

Counter({'compiled': 2, 'user1': 2, 'loggedin': 1, 'user2': 1})

as a result. Is there a way to count tuples with the Counter()? I could concatenate the strings but this is... ugly. Could I use named tuples? Implement my own very simple dictionary counter? Don't know what's best.


回答1:


Sure: you simply have to add one level of indirection, namely pass .update a container with the tuple as an element.

>>> import collections
>>> counter = collections.Counter()
>>> counter.update((('user1', 'loggedin'),))
>>> counter.update((('user2', 'compiled'),))
>>> counter.update((('user1', 'compiled'),))
>>> counter.update((('user1', 'compiled'),))
>>> counter
Counter({('user1', 'compiled'): 2, ('user1', 'loggedin'): 1, ('user2', 'compiled'): 1})


来源:https://stackoverflow.com/questions/11883194/how-to-count-co-ocurrences-with-collections-counter-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!