我是 Python 新手,对 Python 官方文档中的一段代码感到困惑。
unique_words = set(word for line in page for word in line.split())
Run Code Online (Sandbox Code Playgroud)
对我来说,它看起来相当于:
unique_words=set()
for word in line.split():
for line in page:
unique_words.add(word)
Run Code Online (Sandbox Code Playgroud)
在嵌套循环中定义 line 之前,如何在第一个循环中使用它?然而,它确实有效。我认为这表明嵌套列表理解和生成器表达式的顺序是从左到右,这与我之前的理解相矛盾。
任何人都可以为我澄清正确的顺序吗?
我正在阅读着名的K&R书籍,并被1.6中的例子所困扰.
#include <stdio.h>
/* count digits, white space, others */
main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]); …Run Code Online (Sandbox Code Playgroud)