0

我正在尝试使用 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”之后最常见的词是“lazy”。但是,python 会输出 CFD 字典中的最后一个单词,即“快速”。

4

1 回答 1

1

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

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

于 2019-11-06T20:11:03.287 回答