字典中元组平均数的函数

2024-06-09 12:54:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,字典的形式是:

('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。 我不知道我的函数中有什么不允许我得到正确的答案。你知道吗


Tags: theinforstringlenreturniffloat