重叠循环和Python语法

2024-04-19 12:50:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在学习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

我不明白第二行的目的。 此外,我不明白为什么每个循环都不像Python中的任何循环那样以“:”结尾。你知道吗

有人能给我解释一下这个密码吗?代码可以工作,但我不完全理解它的语法。你知道吗

谢谢


Tags: inlooptargetforifcreate语法lower
1条回答
网友
1楼 · 发布于 2024-04-19 12:50:02

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,…)元组是在我们迭代generator对象时逐个生成的。你知道吗

您还可以查看How exactly does a generator comprehension work? ,了解有关生成器表达式的更多信息。你知道吗

相关问题 更多 >