【问题标题】:Dictionary with words as the key and frequencies as the value and finding the highest value in the dictionary with the same length of letters以单词为键,频率为值的字典,找到字典中字母长度相同的最大值
【发布时间】:2016-10-10 08:44:30
【问题描述】:

该函数打印关键字长度,然后打印所有所需长度的字典关键字的排序列表,这些关键字具有最高频率,其次是频率。例如以下代码:

word_frequencies = {"and":15,  "whale":7,  "frog":7,  "cat":15,  "fish":1,  "dog":2,  "pig":15,  "stork":1,  "rat":15,  "bird":7}
print_most_frequent(word_frequencies, 3)
print_most_frequent(word_frequencies, 4)
print_most_frequent(word_frequencies, 5)

打印出来:

3 letter keywords: ['and', 'cat', 'pig', 'rat'] 15
4 letter keywords: ['bird', 'frog'] 7
5 letter keywords: ['whale'] 7

这是我目前的尝试:

def print_most_frequent(words_dict, word_len):
    keyword_length = []
    frequency = 0
    for key in words_dict:
        if len(key) == word_len and words_dict[key] >= frequency:
            keyword_length += [key]
            if frequency != words_dict[key]:
                frequency += words_dict[key]
    print (str(word_len) + " letter keywords: " + str(keyword_length) + " " + str(frequency))

但这给了我:

3 letter keywords: ['dog', 'cat'] 17
4 letter keywords: ['frog', 'bird'] 15
5 letter keywords: ['whale'] 7

谁能指出我正确的方向,让我知道该怎么做。

我需要按字母顺序对字典进行排序,结果如下:

['and', 'cat', 'pig', 'rat']

而不是随机化它。

【问题讨论】:

  • 经验法则:如果变量实际上不包含任何长度(我希望它是一个数字),则不要用“长度”调用任何变量
  • 最后的数字是什么意思?起初我以为这是单词的最大值,但在你的第二个例子中bird 的值为8,但最后的数字是7
  • 对不起,我的意思是放 7

标签: python-3.x sorting dictionary


【解决方案1】:

您可以使用字典推导式创建一个字典,其中的键只有 len 等于 word_len。然后您可以使用max 获取这些项目的最大值。最后,您可以创建一个列表,其中仅包含频率等于最大频率的项目。

您可以使用sorted 按字母顺序对列表进行排序。

word_frequencies = {"and":15,  "whale":7,  "frog":7,  "cat":15,  "fish":1,  "dog":2,  "pig":15,  "stork":1,  "rat":15,  "bird":7}

def print_most_frequent(words_dict, word_len):

    keys = words_dict.keys()
    max_length = max([len(i) for i in keys])  # Find max length of words
    min_length = min([len(i) for i in keys])  # Find min length of words

    if not min_length <= word_len <= max_length:
        print("{} letter keywords: [] -".format(word_len))
        return  # Exit function

    words = {i:j for i,j in words_dict.items() if len(i) == word_len}  # Create a dictionary containing words that are the same length as word_len
    max_value = max(words.values())  # Find the max frequency of the words in the above dictionary
    words_final = sorted([i for i,j in words.items() if j == max_value])  # Create a list of words that have the value of max_value 

    print("{} letter keywords: {} {}".format(word_len, words_final, max_value))

输出:

>>> print_most_frequent(word_frequencies,3)
3 letter keywords: ['and', 'cat', 'pig', 'rat'] 15
>>> print_most_frequent(word_frequencies,4)
4 letter keywords: ['bird', 'frog'] 7
>>> print_most_frequent(word_frequencies,5)
5 letter keywords: ['whale'] 7
>>> print_most_frequent(word_frequencies,10)
10 letter keywords: [] -

您可能需要稍微清理一下代码。但这应该足以让您入门。

【讨论】:

    【解决方案2】:

    您的frequency 变量可能意味着保存maximum frequency。不过,您对此的逻辑是错误的。如果你合并&gt;= 和!=,它会给你:

    • 将max_frequency设置为0
    • 如果下一个单词的frequency 高于此值,则将其frequency 添加到max_frequency
    • 对所有单词重复最后一步

    而我相信你真正想要的是:

    • 将max_frequency设置为0
    • 如果下一个单词的frequency 高于此值,则设置 max_frequency 为该单词的frequency
    • 对所有单词重复最后一步
    • 查找具有该频率的所有单词

    此外,您只将频率等于或高于frequency 的单词添加到列表中。但我认为您想添加具有正确字符数的所有单词。


    长话短说:

        # filter words based on key length
        right_length = {k: v for k, v in words_dict.items() if len(k) == word_len}
        # calculate maximal value (max frequency)
        max_freq = max(right_length.values())
        # filter words with that max frequency
        max_words = {k: v for k, v, in right_length.items if v == max_freq}
        # now max_words contains all words of specified length with the maximum frequency
        # print words alphabetically
        print(sorted(max_words.keys()))
    

    同样的代码更简单:

        # filter words based on key length
        right_length = {}
        for k, v in words_dict.items():
            if len(k) == word_len:
                right_length[k] = v
        # calculate maximal value (max frequency)
        max_freq = max(right_length.values())
        # filter words with that max frequency
        max_words = {}
        for k, v in right_length.items():
            if v == max_freq:
                max_words[k] = v
        # now max_words contains all words of specified length with the maximum frequency
        # print words alphabetically
        print(sorted(max_words.keys()))
    

    【讨论】:

    • 这对我帮助很大,我现在遇到的问题是有多个长度相同但频率不同的单词,例如“fish”:1,我需要忽略它。我还需要按字母顺序对其进行排序,使其变为 ['and', 'cat', 'pig', 'rat'] 而不是每次都随机化。
    • 用于排序将列表包装在sorted() 中。关于只取数量最多的动物,你需要先计算最大的数量。
    • 通过条件内联字典创建更新了答案。使用上面的代码,您将拥有一个逐步过滤系统。首先过滤掉所有长度合适的单词,然后过滤掉频率最高的单词。在结果字典中,您只有以 max_freq 为值的单词。
    • 如果你可以编辑它:for k,v in words_dict.items(): if len(k) == word_len: right_length = {k,v} 或其他东西更容易弄清楚。我只学习了python的基本代码,所以你给我的代码我不容易弄清楚。
    • 如果你试图找到一个长度为 10 的字母,但它没有找到,而是返回一个空列表。我怎么做。因此,如果我尝试查找长度为 10 的单词,它会返回:7 个字母关键字:[]
    猜你喜欢
    • 2015-06-26
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多