要應用功能,對任何輸入的值,你可以使用一個類和方法, 這將是優雅的方式,我不知道你的程序,但你可以重命名類更好的可讀性,根據它實際上代表了什麼(這是在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
和:通過調用
def getCount(counter, key):
sm = 1
s = sum(cnt.values())
c = len(cnt)
return (counter[key] + sm)/(s + (sm * c))
,然後使用它:
In [13]: print(cntc('red'))
0.333333333333
In [14]: print(cntc('blue'))
0.444444444444
是你確定*這是Python 3.5? – user2357112
實際上,「黃色」根本不在您的輸入中。你正在獲得默認計數。這裏沒有任何東西可以將'cnt [k] =(cnt [k] + sm)/(s +(sm * c))'計算應用於'cnt ['yellow']'。 – user2357112
我想通過這個計算將這個默認零點改爲正值。有什麼我可以做的。 –