我是Python的新手,我想知道代码是否可行:
IFRDocument document = engine.CreateFRDocument();
document.Export(filePath, FileExportFormatEnum.FEF_DOCX, irtfExportParams);
这些说明旨在根据我在其他编程语言中的知识来创建字典,我了解每次循环都将进行计数,因此我想做的是优化而不是计数如果这个词已经算过了。
现在的问题是我遇到了这个错误
chs = ch.split(' ')
d = { mot:ch.count(mot) for mot in chs if (mot not in d)}
我完全理解,变量NameError: free variable 'd' referenced before assignment in enclosing scope
尚未设置。
所以,我要寻找的是知道是否有一些临时变量的值包含在机箱前。
答案 0 :(得分:2)
您可能会这样做:
ch = 'a a b c d'
words = set(ch.split(' '))
d = { mot:ch.count(mot) for mot in words}
print(d)
创建一个set
个单词。这样,您只需检查一次唯一的单词。
答案 1 :(得分:0)
您根本不需要检查mot
中是否存在d
。
ch = 'a a b c d'
chs = ch.split(' ')
d = { mot:ch.count(mot) for mot in chs }
现在d = {'a': 2, 'b': 1, 'c': 1, 'd': 1}
。