python中嵌套列表理解和嵌套生成器表达式的顺序 [英] The order of nested list comprehension and nested generator expression in python

查看:219
本文介绍了python中嵌套列表理解和嵌套生成器表达式的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,并被Python官方文档中的一段代码弄糊涂了.

I'm new to Python and is confused by a piece of code in Python's official documentation.

unique_words = set(word  for line in page  for word in line.split())

在我看来,它等同于:

unique_words=set()
for word in line.split():
    for line in page:
        unique_words.add(word)

在嵌套循环中定义line之前,如何在第一个循环中使用line?但是,它实际上有效.我认为这表明嵌套列表理解和生成器表达的顺序是从左到右,这与我以前的理解相矛盾.

How can line be used in the first loop before it's defined in the nested loop? However, it actually works. I think it suggests the order of nested list comprehension and generator expression is from left to right, which contradicts with my previous understanding.

任何人都可以为我澄清正确的顺序吗?

Can anyone clarify the correct order for me?

推荐答案

word for line in page for word in line.split()

此部分的工作方式如下:-

this part works like this:-

for line in page:
    for word in line.split():
        print word

()这使其具有生成器功能 因此,总体的陈述工作是这样的:-

() this makes it `generator function hence overall statement work lie this:-

def solve():
    for line in page:
        for word in line.split():
            yield word

和set()用于避免重复或重复同一单词,因为该代码旨在获取唯一单词".

and set() is used to avoid duplicacy or repetition of same word as the code is meant to get 'unique words'.

这篇关于python中嵌套列表理解和嵌套生成器表达式的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆