我会堆叠生成器表达式:
with open(filename) as f_in:
lines = (line.rstrip() for line in f_in) # All lines including the blank ones
lines = (line for line in lines if line) # Non-blank lines
现在,行是所有非空白行.这样可以避免两次调用线路上的条带.如果你想要一个行列表,那么你可以这样做:
with open(filename) as f_in:
lines = (line.rstrip() for line in f_in)
lines = list(line for line in lines if line) # Non-blank lines in a list
你也可以用单行代码(exlude with statement)来实现它,但它不再有效且难以阅读:
with open(filename) as f_in:
lines = list(line for line in (l.strip() for l in f_in) if line)
更新:
我同意这是因为重复令牌而丑陋.如果您愿意,您可以编写一个生成器:
def nonblank_lines(f):
for l in f:
line = l.rstrip()
if line:
yield line
然后称之为:
with open(filename) as f_in:
for line in nonblank_lines(f_in):
# Stuff
更新2:
with open(filename) as f_in:
lines = filter(None, (line.rstrip() for line in f_in))
并在CPython上(具有确定性引用计数)
lines = filter(None, (line.rstrip() for line in open(filename)))
在Python 2中使用itertools.ifilter如果你想要一个生成器,在Python 3中,如果你想要一个列表,只需将整个事物传递给列表.