是否有一种 pythonic 方法来计算数组中每个元素的出现次数?
Is there a pythonic way of counting the occurrences of each element in an array?
正如标题所暗示的,我只是想知道是否有一种pythonic方式来计算数组中每个元素的出现次数。我已经实现了下面的代码:
my_array = ['dog', 'cat', 'rabbit', 'rabbit', 'elephant', 'bee', 'dog', 'cat', 'cat', 'elephant']
occurrences = {}
for item in my_array:
try:
occurrences[item] += 1
except KeyError:
occurrences[item] = 1
它给了我 ff 结果:
dog: 2
cat: 3
rabbit: 2
elephant: 2
bee: 1
是否有更 pythonic 的方式来做到这一点?
PS:抱歉这个问题有点愚蠢。如果有人同意,我可能会删除它。
PPS:如果这个问题重复了,你能不能把link去掉,我试试看。 :)
Counter
来自标准库中的 collections
模块就是您要查找的内容。
https://docs.python.org/3/library/collections.html#collections.Counter
这样使用:
from collections import Counter
my_array = ['dog', 'cat', 'rabbit', 'rabbit', 'elephant', 'bee', 'dog', 'cat', 'cat', 'elephant']
c = Counter(my_array)
C
然后 returns
Counter({'cat': 3, 'dog': 2, 'rabbit': 2, 'elephant': 2, 'bee': 1})
您还可以将其转换为元素字典:计数。
dict(c)
正如标题所暗示的,我只是想知道是否有一种pythonic方式来计算数组中每个元素的出现次数。我已经实现了下面的代码:
my_array = ['dog', 'cat', 'rabbit', 'rabbit', 'elephant', 'bee', 'dog', 'cat', 'cat', 'elephant']
occurrences = {}
for item in my_array:
try:
occurrences[item] += 1
except KeyError:
occurrences[item] = 1
它给了我 ff 结果:
dog: 2
cat: 3
rabbit: 2
elephant: 2
bee: 1
是否有更 pythonic 的方式来做到这一点?
PS:抱歉这个问题有点愚蠢。如果有人同意,我可能会删除它。
PPS:如果这个问题重复了,你能不能把link去掉,我试试看。 :)
Counter
来自标准库中的 collections
模块就是您要查找的内容。
https://docs.python.org/3/library/collections.html#collections.Counter
这样使用:
from collections import Counter
my_array = ['dog', 'cat', 'rabbit', 'rabbit', 'elephant', 'bee', 'dog', 'cat', 'cat', 'elephant']
c = Counter(my_array)
C
然后 returns
Counter({'cat': 3, 'dog': 2, 'rabbit': 2, 'elephant': 2, 'bee': 1})
您还可以将其转换为元素字典:计数。
dict(c)