所以我编写了一个超级简单的计数器来返回字母比例:
def hasnoe(word):
count = 0
for letter in word:
if letter == 'e':
count += 1.0
ratio = count / (len(word))
return ratio
hasnoe('eeeeeeheif')
但是当我试用它时,计算机没有返回任何值 - 这是什么?
答案 0 :(得分:3)
您不能从函数返回多次。您目前在循环的第一个字母后返回count
,因此它只能是0
或1
。
要解决此问题,您只需删除return count
def hasnoe(word):
count = 0
for letter in word:
if letter == 'e':
count += 1.0
ratio = count/(len(word))
return ratio
>>> hasnoe('eeeeeeheif')
0.7
答案 1 :(得分:1)
>>> from collections import Counter
>>> s = 'eeeeeeheif'
>>> c = Counter(s)
>>> c
Counter({'e': 7, 'i': 1, 'h': 1, 'f': 1})
>>> den = float(len(s))
>>> freq = dict((k, v/den) for k, v in c.iteritems())
>>> freq
{'i': 0.1, 'h': 0.1, 'e': 0.7, 'f': 0.1}
答案 2 :(得分:0)
尝试使用此代码返回两次
def hasnoe(word):
count = 0
for letter in word:
if letter == 'e':
count += 1.0
ratio = count/(len(word))
return ratio
hasnoe('eeeeeeheif')
答案 3 :(得分:0)
如果你想要两个号码,你最好的选择是返回一个元组。
def hasnoe(word):
count = 0
for letter in word:
if letter == 'e':
count += 1.0
ratio = count/(len(word))
return ratio, count
ratio, count = hasnoe('eeeeeeheif')