2012-10-18 43 views
-2

我如何写一个Python程序,与任何字符串的输入和字典的形式取值为字符串在词典:计算平均分数在一本字典的字符串

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

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

+1

那么该字符串是如何解释的? –

+1

示例中字符串的值是什么?你有什么尝试? – StoryTeller

+1

您究竟想要在这里计算平均值? –

回答

2

它看起来像你对我想:

def score(key_str,dct): 
    keys = key_str.split() 
    v = sum(dct[key] for key in keys) 
    return float(v)/len(keys) 
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 
+0

+1 haha​​ha不错的一个 –