可以将其转换为列表理解吗?

时间:2019-06-07 02:10:07

标签: python

下面的函数从URL的文本文件返回单词列表:

def fetch_words():
    with urlopen('http://sixty-north.com/c/t.txt') as story:
        story_words = []
        for line in story:
            line_words = line.decode('utf-8').split()
            for word in line_words:
                story_words.append(word)
    return story_words

我很想看看是否可以将其转换为等效的列表理解方法。我尝试过:

with urlopen('http://sixty-north.com/c/t.txt') as story:
     return [word for word in line.decode('utf-8').split() 
             for line in story]

,但出现“未解析的参考'行'”错误。看来我误会了嵌套列表理解的工作原理,有人可以解释吗?

3 个答案:

答案 0 :(得分:2)

您的语法略有错误,请尝试以下操作:

return [word for line in story for word in line.decode('utf-8').split()]

答案 1 :(得分:2)

当列表理解有两个循环时,它们的顺序必须与语句的顺序相同:

with urlopen('http://sixty-north.com/c/t.txt') as story:
    return [
        word 
        for line in story
        for word in line.decode('utf-8').split() 
    ]

答案 2 :(得分:2)

为简单起见,我建议使用requests模块:

<question-host *ngFor="let question of questions" [question]="question" hidden></question-host>

不需要上下文管理器。


如果您要读取的数据很小,则可以使用

story_words = [
    word 
    for line in requests.get('http://sixty-north.com/c/t.txt').iter_lines() 
    for word in line.decode('utf-8').split()
]