-2

次の形式の任意の文字列と辞書の入力を使用して、辞書内の文字列の値を取得するPythonプログラムを作成するにはどうすればよいですか?

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

値の平均をfloatとして返しますか?

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 に答える