我将堆栈生成器表达式:
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
现在,
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
您也可以采用单行代码(排除
with语句)来执行此 *** 作,但是它不再高效且更难阅读:
更新: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
然后像这样调用它:
更新2:with open(filename) as f_in: for line in nonblank_lines(f_in): # Stuff
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)))
itertools.ifilter如果需要生成器,请在Python 2中使用;如果需要列表,请在Python 3
list中使用。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)