计算字典中字符串的分数平均值

时间:2012-10-18 19:54:06

标签: python string dictionary average

如何编写一个python程序,它接受字典中字符串的值,并在表单中输入任何字符串和字典:

score("a b" , {"a":(1.2) , "b":(3.4)})

并将值的平均值作为float返回?

2 个答案:

答案 0 :(得分:2)

在我看来,你想要:

def score(key_str,dct):
    keys = key_str.split()
    v = sum(dct[key] for key in keys)
    return float(v)/len(keys)

答案 1 :(得分:2)

这是一个不那么抽象的答案。

def score(hairypeople, hair_length):
    """ Calculates the average nosehair length given a string of people's names 
    and a dictionary of the length of their nose hairs.  """ 
    list_of_hairy_people = hairypeople.split()
    number_of_hairy_people = len(list_of_hairy_people)
    sum_length_of_hairs = sum([hair_length[ew] for ew in list_of_hairy_people])
    return float(sum_length_of_hairs) / number_of_hairy_people