“with” keyword in list comprehension? [duplicate]

人走茶凉 提交于 2019-12-11 01:03:45

问题


I came across this syntax for reading the lines in a file.

with open(...) as f:
    for line in f:
        <do something with line>

Say I wanted the <do something with line> line to append each line to a list. Is there any way to accomplish this, using the with keyword, in a list comprehension? Or, is there at least some way of doing what I want in a single statement?


回答1:


You can write something like

with open(...) as f:
    l = [int(line) for line in f]

but you can't put the with into the list comprehension.

It migth be possible to write something like

l = [int(line) for line in open(...).read().split("\n")]



回答2:


with uses a function as a context manager, so no. f has no value until inside the block. The best you could do is a 2 line implementation.



来源:https://stackoverflow.com/questions/43619143/with-keyword-in-list-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!