'ImportError: cannot import name Counter
I have tried using Counter() but everytime I do:
from collections import Counter
I get an error saying:
Traceback (most recent call last):
File "<web session>", line 1, in <module>
ImportError: cannot import name Counter
Do I actually have to make a file that has counter in it and then import it from there or something? I am a beginner so only the most basic answer will do.
Solution 1:[1]
Counter is only supported python2.7 and higher and is not available in earlier versions.
Solution 2:[2]
Use
from collections import Counter
and be sure that the C letter of Counter is a capital letter.
Solution 3:[3]
You can just cast the list to a set instead:
l = ['a','b', 'c', 'a', 'd', 'e', 's', 'd', 'e', 'c']
print (len(set(l)) #prints 6
Solution 4:[4]
I don't think that you want to use Counter from collections. Counter is used when you want to do something like count the number of occurrences of each word. For example:
from collections import Counter
Counter(['dog','cat','dog']) # Should output Counter({'dog': 2, 'cat': 1})
To count the number of distinct words in a list, you might try using the following:
len(set(yourList))
of to avoid duplicates with different cases:
len(set(word.lower() for word in yourList))
A set is allowed to contain only one instance of the items it contains, unlike a list.
You might have an earlier version of Python that doesn't include Counter in the standard library. If that is the case, you should update to a newer version if you can.
Solution 5:[5]
Rename your file as may your file named as collections or Counter. After that this will works
Solution 6:[6]
In Python3
import collections
a=collections.Counter(list(i for i in input()))
print(a)
input-
aaabbbcccc
output-
Counter({'c': 4, 'a': 3, 'b': 3})
if you want elements then use a.elements() , for getting values use a.values()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sharafjaffri |
| Solution 2 | zx485 |
| Solution 3 | Jacob |
| Solution 4 | Ken |
| Solution 5 | amit114920 |
| Solution 6 | nucsit026 |
