【问题标题】:Function for averages of tuples in a dictionary字典中元组平均值的函数
【发布时间】: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 / 45.875...
  • @zigg 不,它应该是 5.5 因为对于给定的字符串 'the head' 5.0 + 6.0 / 25.5
  • 哦,好的,我现在明白了。从你的描述中我不清楚你想要达到什么目的——我认为你只是忽略了字符串,就像你忽略了元组的后半部分一样。

标签: python string dictionary tuples average


【解决方案1】:
def score(s, d):
    included = [d[word][0] for word in d if word in s]
    return sum(included) / float(len(included))

【讨论】:

    猜你喜欢
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多