简体   繁体   English

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

[英]string number average returned in string format

Here are some tests: 以下是一些测试:

Input: "zero nine five two" 输入: "zero nine five two"

Output: "four" 输出: "four"

Input: "four six two three" 输入: "four six two three"

Ouput: "three" 乌普特: "three"

Here is my code, which works until the last step where I need to inverse lookup key by value, which I dont know how to do. 这是我的代码,它可以工作到最后一步,在该步骤中我需要按值逆向查找键,而我不知道该怎么做。 Any advice? 有什么建议吗?

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

You can try this: 您可以尝试以下方法:

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]

Output: 输出:

four

Why not just utilize a list of words to represent the numbers where the index represents their respective value? 为什么不仅仅使用单词表来表示数字,而索引代表它们各自的值呢?

def average_string(s):
    num_list = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
    str_split = s.split()
    int_sum = sum(map(num_list.index, str_split))
    return num_list[int_sum / len(str_split)]

The map goes over each element in str_split and translates it into the numeric version by calling num_list.index() using each element as a parameter. 该映射遍历str_split每个元素,并通过使用每个元素作为参数调用num_list.index()将其转换为数字版本。

Finally using the same num_list , use the average value as the index to get the string version back. 最后,使用相同的num_list ,将平均值用作索引以获取字符串版本。

Here is how you inverse a dictionary. 这是您如何反转字典的方法。 This is a duplicated question though: 但是,这是一个重复的问题:

inv_dic = {v: k for k, v in num_dic.items()}

As far as I know there isn't a way to lookup in a dict by value. 据我所知,没有一种方法可以按值查找字典。 Instead you can loop over the dict to find the correct value like this: 相反,您可以遍历dict来找到正确的值,如下所示:

for text, number in num_dic.iteritems():
    if number == int_avg:
        print text

Here is another question where you can find this: Get key by value in dictionary 这是您可以找到的另一个问题: 按字典中的值获取密钥

You can use num_dic.items() in Python 3 您可以在Python 3中使用num_dic.items()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM