Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用内置的max函数输出python CFD字典中最常用的项?_Python_Defaultdict_Cfdirectory - Fatal编程技术网

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

如何使用内置的max函数输出python CFD字典中最常用的项?,python,defaultdict,cfdirectory,Python,Defaultdict,Cfdirectory,我试图使用max在python CFD字典中查找附加到键的最大值。通过这个网站()我相信max可以正确地找到CFD值。然而,我发现当CFD字典中项目的频率发生变化时,它似乎不会得到正确的结果 我是python新手,我想我可能只是对如何调用数据感到困惑。我试着对列表进行排序,相信我可以对键中的值进行排序,但我也不太明白如何进行排序 words = ('The quick brown fox jumped over the ' 'lazy the lazy the lazy dog

我试图使用max在python CFD字典中查找附加到键的最大值。通过这个网站()我相信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字典上输出最后一个单词,即“quick”。

您的问题是CFD['The']是一个dict,当max对它进行原始迭代时,它实际上只对键进行迭代。在这种情况下,“quick”大于“lazy”,因为字符串


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

如果您在某个地方定义了首字母缩写词cfd,这个问题将得到很大改进。对于其他像我一样困惑的人:CFD=条件频率分布