我尝试使用Counter(),但每次都出现问题:
from collections import Counter
我收到一个错误,其中显示:
Traceback (most recent call last):
File "<web session>", line 1, in <module>
ImportError: cannot import name Counter
我真的需要创建一个包含计数器的文件,然后从那里导入它吗?因为我是初学者,所以只需要最基本的答案。
我尝试使用Counter(),但每次都出现问题:
from collections import Counter
我收到一个错误,其中显示:
Traceback (most recent call last):
File "<web session>", line 1, in <module>
ImportError: cannot import name Counter
我真的需要创建一个包含计数器的文件,然后从那里导入它吗?因为我是初学者,所以只需要最基本的答案。
计数器仅支持 Python 2.7 及更高版本,不支持早期版本。
使用
from collections import Counter
请确保 Counter
中的 C
是大写字母。
set
:l = ['a','b', 'c', 'a', 'd', 'e', 's', 'd', 'e', 'c']
print (len(set(l)) #prints 6
我认为你不想使用collections中的Counter。当你想要做一些类似统计每个单词出现次数的操作时,可以使用Counter。例如:
from collections import Counter
Counter(['dog','cat','dog']) # Should output Counter({'dog': 2, 'cat': 1})
如果要计算列表中不同单词的数量,可以尝试使用以下代码:
len(set(yourList))
如何避免不同大小写的重复:
len(set(word.lower() for word in yourList))
集合只允许包含一个实例,而列表则不同。
如果您使用的是早期版本的Python,可能没有在标准库中包含Counter。如果是这种情况,建议尽可能升级到新版本。
在Python3中
import collections
a=collections.Counter(list(i for i in input()))
print(a)
输入 -
aaabbbcccc
输出 -
Counter({'c':4,'a':3,'b':3)}
如果你想要元素,则使用a.elements()
,获取值则使用a.values()