如何将计数器值除以设定数字?

时间:2019-11-11 16:54:04

标签: python counter

我一直在计算使用collections.Counter在列表中出现的单词数。但是我的问题是我现在正在寻找将每个值除以预定数字(在这种情况下为14)。但是,我正在尝试以下操作,但遇到了错误:'str' object has no attribute 'values',据我所知,但不确定如何更正。这是我目前拥有的:

from collections import Counter
mylist = ['red','green','blue','red','orange','red','green']

counts = Counter(mylist)

for word in counts:
    x = word.values()/14

理想情况下,我想最终得到的是字典列表,其中单词作为键,而计数(除以我的预设值)作为值。像

>>> mynewlist = [{'Red', 0.214},{'Green', 0.143},{'Blue', 0.071},{'Orange', 0.071}]

1 个答案:

答案 0 :(得分:3)

您必须像在普通词典上一样对它进行迭代:

from collections import Counter
mylist = ['red','green','blue','red','orange','red','green']

counts = Counter(mylist)
for item, count in counts.items():
    counts[item] /= 14

print(counts)
# Counter({'red': 0.21428571428571427, 'green': 0.14285714285714285, 
# 'blue': 0.07142857142857142, 'orange': 0.07142857142857142})