这能转换成一个列表吗?

2024-04-18 16:01:20 发布

您现在位置: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]

但它的错误是“未解析的引用‘线’”。我好像误解了嵌套列表理解的工作原理,有人能解释一下吗?你知道吗


Tags: intxtcomhttp列表foraswith
3条回答

为简单起见,我建议使用^{}模块:

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()
]

不需要上下文管理器。你知道吗


如果你读取的数据相当小,你可以使用

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

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

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() 
    ]

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

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

相关问题 更多 >