我有一些代码可以读取名称文件并创建列表:
names_list = open("names", "r").read().splitlines()
每个名称用换行符分隔,如下所示:
Allman Atkinson Behlendorf
我想忽略仅包含空格的任何行。我知道我可以通过以下方式来实现:创建一个循环并检查读取的每一行,然后将其添加到列表(如果不是空白的话)。
我只是想知道是否还有更Pythonic的方法?
我将堆栈生成器表达式:
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是所有非空白行。这将使您不必在线路上两次打电话。如果需要行列表,则可以执行以下操作:
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
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
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 3list中使用。
itertools.ifilter
list