Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算字典中字符串的平均分数_Python_String_Dictionary_Average - Fatal编程技术网

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

我如何编写一个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

该字符串是如何解释的?示例中该字符串的值是多少?你试过什么?你到底想计算这里的平均值是多少?@gnibler——我明白了。删除了我的评论。