我有一些代码可以读取名称文件并创建列表:

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是所有非空白行。这将使您不必在线路上两次打电话。如果需要行列表,则可以执行以下操作:
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)

更新:

我同意,由于 token 的重复,这很丑陋。您可以根据需要编写一个生成器:
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中,如果需要列表,只需将整个内容传递给list

关于python - 在Python中读取文件时忽略空行的最简单方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4842057/

10-13 04:38