次の形式の任意の文字列と辞書の入力を使用して、辞書内の文字列の値を取得するPythonプログラムを作成するにはどうすればよいですか?
score("a b" , {"a":(1.2) , "b":(3.4)})
値の平均をfloatとして返しますか?
次の形式の任意の文字列と辞書の入力を使用して、辞書内の文字列の値を取得するPythonプログラムを作成するにはどうすればよいですか?
score("a b" , {"a":(1.2) , "b":(3.4)})
値の平均をfloatとして返しますか?
あなたが望むように私には見えます:
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