python - 以字符串格式返回的字符串数平均值

标签 python dictionary iteration key-value

以下是一些测试:

输入:“零九五二”

输出:“四”

输入:“四六二三”

输出:“三”

这是我的代码,直到最后一步我需要按值反向查找键,我不知道该怎么做。有什么建议吗?

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/

相关文章:

c++ - Ogre3d:遍历子节点错误

python - Django Rest Framework 只读模型序列化程序

Android:设置 map Intent 的缩放

java - 检索与字符串同名的变量

python - 删除列表中字符串的所有扩展名

c++ - 如何在 STL map 内迭代 STL map ?

python程序无法在cmd中运行

python - Spark 读取二进制文件的子组

python - 使用多个列表作为函数的输入参数 (Python)

c - 迭代 C 字符串不起作用