代码的输出值是cnt ['yellow'] = 0但是应用代码中给出的公式后的期望值应为(0 +1)/(6 +(1 * 3))
from collections import Counter
cnt = Counter()
sm = 1
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
s = sum(cnt.values())
print(s)
c = len(cnt)
print(c)
for k,v in cnt.items():
cnt[k] = (cnt[k] + sm)/(s + (sm *c))
print(cnt['yellow'])
答案 0 :(得分:1)
要将函数应用于任何输入的值,您可以使用类和方法, 这将是优雅的方式,我不知道你的程序,但你可以重命名类以获得更好的可读性,根据它实际上代表这样(这是在py2中测试但应该在py3中工作):
from collections import Counter
lst1 = ['red', 'blue', 'red', 'green', 'blue', 'blue']
class count_helper:
def __init__(self):
self.sm = 1.0
self.cnt = Counter()
def count_colors(self,lst):
for w in lst:
self.cnt[w]+=1.0
def __call__(self,color='blank'):
s = sum(self.cnt.values())
c = len(self.cnt)
return (self.cnt[color] + self.sm)/(s + (self.sm *c))
cntc = count_helper()
cntc.count_colors(lst1)
print(cntc('yellow'))
<强>结果:强>
0.111111111111
并且:
In [13]: print(cntc('red'))
0.333333333333
In [14]: print(cntc('blue'))
0.444444444444
答案 1 :(得分:0)
您可以添加自定义方法,例如:
def getCount(counter, key):
sm = 1
s = sum(cnt.values())
c = len(cnt)
return (counter[key] + sm)/(s + (sm * c))
然后通过致电:
使用它print getCount(cnt, "yellow")