[英]how do I convert a list into a counter object in python
I have a list which looks like this: 我有一个如下所示的列表:
myList = [('string1', 48), ('string2', 48), ('string3', 18)]
how can I convert this into a counter? 我该如何将其转换为计数器? I've already this:
我已经这样了:
newCounter = Counter(myList)
but I seem to still be getting a list 但我似乎仍然得到一份清单
You're definitely not getting a list. 你肯定没有得到一份清单。 You're not getting the Counter you want, because the Counter constructor will count an iterable it's provided instead of treating it as a list of key-value pairs, so turn the list into a dict first to get around that:
你没有得到你想要的计数器,因为Counter构造函数将计算它提供的迭代,而不是将其视为键值对列表,因此首先将列表转换为dict以解决这个问题:
counter = Counter(dict(myList))
If you're sure you're getting a list, you have some other bug we can't see. 如果您确定要获得列表,那么您还有其他一些我们看不到的错误。
If you print newCounter
you'll be able to see it's already a counter object: 如果您打印
newCounter
您将能够看到它已经是一个反对象:
Counter({('string3', 18): 1, ('string1', 48): 1, ('string2', 48): 1})
Also see the type of newCounter
: 另见
newCounter
的类型:
print type(newCounter)
<class 'collections.Counter'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.