-2

如何编写一个 python 程序来获取字典中字符串的值,并输入以下形式的任何字符串和字典:

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

并将值的平均值作为浮点数返回?

4

2 回答 2

2

它看起来像你想要的:

def score(key_str,dct):
    keys = key_str.split()
    v = sum(dct[key] for key in keys)
    return float(v)/len(keys)
于 2012-10-18T20:08:35.257 回答
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
于 2012-10-18T20:16:04.493 回答