Python 计算字典中字符串的平均分数
我如何编写一个python程序,以任何字符串和字典的形式输入字典中的字符串值:Python 计算字典中字符串的平均分数,python,string,dictionary,average,Python,String,Dictionary,Average,我如何编写一个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(ha
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
该字符串是如何解释的?示例中该字符串的值是多少?你试过什么?你到底想计算这里的平均值是多少?@gnibler——我明白了。删除了我的评论。