这是一些测试:

输入:"zero nine five two"

输出:"four"

输入:"four six two three"

输出:"three"

这是我的代码,可以运行到最后一步,在该步骤中我需要按值逆向查找键,而我不知道该怎么做。有什么建议吗?

def average_string(s):
    num_dic = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5,
    'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}
    str_split = s.split()
    int_values = []
    for key, val in num_dic.items():
        if key in str_split:
            int_values.append(val)
            int_avg = int(sum(int_values) / len(int_values))
    return int_avg

最佳答案

您可以尝试以下方法:

num_dic = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}

s = "zero nine five two"

new_dict = {b:a for a, b in num_dic.items()}

average = sum(num_dic[i] for i in s.split())/float(len(s.split()))

final_average = new_dict[average]


输出:

four

关于python - 以字符串格式返回的平均字符串数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45361727/

10-12 22:09