如何编写一个 python 程序来获取字典中字符串的值,并输入以下形式的任何字符串和字典:
score("a b" , {"a":(1.2) , "b":(3.4)})
并将值的平均值作为浮点数返回?
如何编写一个 python 程序来获取字典中字符串的值,并输入以下形式的任何字符串和字典:
score("a b" , {"a":(1.2) , "b":(3.4)})
并将值的平均值作为浮点数返回?
它看起来像你想要的:
def score(key_str,dct):
keys = key_str.split()
v = sum(dct[key] for key in keys)
return float(v)/len(keys)
这是一个不太抽象的答案。
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