问题
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