【发布时间】:2012-10-20 22:38:35
【问题描述】:
我有一个字符串,字典格式为:
('the head', {'exploded': (3.5, 1.0), 'the': (5.0, 1.0),
"puppy's": (9.0, 1.0), 'head': (6.0, 1.0)})
每个括号是一个对应于(分数,标准差)的元组。我只取每个元组中第一个整数的平均值。我试过这个:
def score(string, d):
for word in d:
(score, std) = d[word]
d[word]=float(score),float(std)
if word in string:
word = string.lower()
number = len(string)
return sum([v[0] for v in d.values()]) / float(len(d))
if len(string) == 0:
return 0
当我跑步时:
print score('the head', {'exploded': (3.5, 1.0), 'the': (5.0, 1.0),
"puppy's": (9.0, 1.0), 'head': (6.0, 1.0)})
我应该得到5.5,但我得到的是5.875。
无法弄清楚我的函数中有什么不允许我得到正确的答案。
【问题讨论】:
-
您在用于计算平均值的函数中的
for循环中有return语句。此外,结果取决于字典上的迭代顺序。很明显,有些不对劲。提示:您正在混合计算单独的术语和整个答案。在循环中查看单独的单词,您应该得到它们对分数的贡献,而不是最终答案。 -
你确定你不应该得到
5.875吗?3.5 + 5.0 + 9.0 + 6.0 / 4是5.875... -
@zigg 不,它应该是
5.5因为对于给定的字符串'the head'5.0 + 6.0 / 2是5.5 -
哦,好的,我现在明白了。从你的描述中我不清楚你想要达到什么目的——我认为你只是忽略了字符串,就像你忽略了元组的后半部分一样。
标签: python string dictionary tuples average