如何使用内置的max函数在python CFD词典中输出最常用的项目?

问题描述 投票:0回答:2

我正在尝试使用max来查找输出,该输出是python CFD词典中某个键的最高附加值。我被认为在此网站(https://www.hallada.net/2017/07/11/generating-random-poems-with-python.html)中可以使用max来正确找到CFD值。但是,我发现更改CFD词典中项目的频率似乎无法获得正确的结果。

我是python的新手,我想我可能对如何调用数据感到困惑。我尝试对列表进行排序,以为我可以获取要排序的键中的值,但是我也不认为该怎么做。

words = ('The quick brown fox jumped over the '
         'lazy the lazy the lazy dog and the quick cat').split(' ')
from collections import defaultdict
cfd = defaultdict(lambda: defaultdict(lambda: 0))
for i in range(len(words) - 2):  # loop to the next-to-last word
    cfd[words[i].lower()][words[i+1].lower()] += 1

{k: dict(v) for k, v in dict(cfd).items()}
max(cfd['the'])

[the]之后最常见的词是“懒惰”。但是,python在CFD词典上输出最后一个单词,即“快速”。

python defaultdict cfdirectory
2个回答
1
投票

您的问题是cfd ['the']是一个命令,当max对其原始进行迭代时,它实际上仅对键进行了迭代。在这种情况下,“快速”大于“惰性”,因为字符串。

将最大值更改为:max(cfd['the'].items(), key=lambda x: x[1])


0
投票

调用max(cfd['the'])时,它会在cfd['the']字典中找到“最大值” key,而不是具有最大值的键。

您可以按照.iteritems()的说明使用operator.itemgetterhere的组合来完成所需的工作:

max(cfd['the'].iteritems(), key=operator.itemgetter(1))[0]

或在python3中(带有.items()):

max(cfd['the'].items(), key=operator.itemgetter(1))[0]
© www.soinside.com 2019 - 2024. All rights reserved.