Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
意外的python计数器值_Python_Python 3.5 - Fatal编程技术网

意外的python计数器值

意外的python计数器值,python,python-3.5,Python,Python 3.5,代码的输出值为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

代码的输出值为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'])

要将函数应用于任何输入的值,可以使用类和方法, 这将是一种优雅的方式,我不知道您的程序,但您可以根据类实际表示的内容重命名该类以提高可读性。该类在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'))
结果:

以及:


您可以添加自定义方法,如:

def getCount(counter, key):
  sm = 1
  s = sum(cnt.values())
  c = len(cnt)
  return (counter[key] + sm)/(s + (sm * c))
然后通过调用以下命令来使用它:

print getCount(cnt, "yellow")

您确定这是Python3.5吗?实际上,“黄色”根本不在您的输入中。您将获得默认计数。这里没有任何东西可以将您的cnt[k]=cnt[k]+sm/s+sm*c计算应用于cnt['yellow']。我想通过此计算将此默认值更改为正值。我能做些什么吗。请告诉我是否有人可以在不使用类的情况下共享此问题的工作来操作计数器的默认值。这将非常有帮助。请解释使用面向对象编程来获得所需结果的原因需要为任何输入函数执行函数的方法时,计数器对象必须保存其他值、列表/你可以单独保存计数器,但那会很难看,更优雅的形式是将它封装在其他更大的对象中,他的方法之一是打印要求的公式,我将更新我的答案,以强调这一点。
def getCount(counter, key):
  sm = 1
  s = sum(cnt.values())
  c = len(cnt)
  return (counter[key] + sm)/(s + (sm * c))
print getCount(cnt, "yellow")