叠层循环和 Python 语法

Imbricated loops and Python syntax

我目前正在 Python 学习 NLP,我遇到了 Python 语法的问题。

cfd = nltk.ConditionalFreqDist( #create conditional freq dist
    (target, fileid[:4]) #create target (Y) and years (X)
    for fileid in inaugural.fileids() #loop through all fileids
    for w in inaugural.words(fileid) #loop through each word of each fileids 
    for target in ['america','citizen'] #loop through target
    if w.lower().startswith(target)) #if w.lower() starts with target words
cfd.plot() # plot it

我不明白第 2 行的目的。 此外,我不明白为什么每个循环不像 Python.

中的任何循环那样以“:”结尾

谁能给我解释一下这段代码?代码有效,但我不完全理解它的语法。

谢谢

nltk.ConditionalFreqDist 的参数是 generator expression

语法类似于列表理解的语法:我们可以用

创建一个列表
[(target, fileid[:4])  for fileid in inaugural.fileids()
                       for w in inaugural.words(fileid) 
                       for target in ['america','citizen'] 
                       if w.lower().startswith(target) ]

并将其传递给函数,但使用生成器可以提高内存效率,因为我们不必在迭代之前构建整个列表。相反,当我们迭代生成器对象时,(target, ...) 元组一个一个地生成。

您还可以查看 生成器理解究竟是如何工作的? 了解有关生成器表达式的更多信息。