如何计算与collection.Counter()在python中的共同? [英] How to count co-ocurrences with collections.Counter() in python?

查看:460
本文介绍了如何计算与collection.Counter()在python中的共同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解了 collections.Counter()类最近,因为它是一个整洁(和快速??)的方式来计数的东西,我开始使用它。

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.

,如果你运行:

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

print counter

您将获得:

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

。有没有办法用Counter()计数元组?我可以连接字符串,但这是...丑陋。我可以使用命名元组吗?实现我自己的非常简单的字典计数器?不知道最好的。

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.

推荐答案

当然:你只需要添加一个间接级别,即pass .update 一个以元组为元素的容器。

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})

这篇关于如何计算与collection.Counter()在python中的共同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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