从文件到行列表

时间:2014-05-26 11:42:04

标签: python file list-comprehension

我知道如何使用以下方法从单个文件中提取行:

lines = [line.rstrip("\n") for line in open(infile)]

我希望将其推广到多个输入文件。我可以想办法用两个for循环来做到这一点,但我想知道是否有类似的可爱的' ' pythonesque'在一条线上做的方式。有点像:

lines = [line.rstrip("\n") for line in open(infile) for infile in infiles]

(遗憾的是,它不起作用......)

3 个答案:

答案 0 :(得分:2)

您的订单已关闭:

lines = [line.rstrip("\n") for infile in infiles for line in open(infile)]

如果你按照自己的方式打电话:

>>> lines = [line.rstrip("\n") for line in open(infile) for infile in infiles]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'infile' is not defined
>>> 

就像使用for循环一样,使用list comprehension:

for infile in infiles:
    for line in open(infile):
        lines.append(line.rstrip("\n"))

答案 1 :(得分:1)

只需更换for循环的顺序即可开始工作:

lines = [line.rstrip("\n") for infile in infiles for line in open(infile)]

列表推导循环必须按嵌套顺序列出;如果您将嵌套循环,如:

for infile in infiles:
    for line in open(infile):

那么这也是列表理解中的顺序。

答案 2 :(得分:1)

首先,您需要切换for语句。

lines = [line.rstrip("\n") for line in open(infile) for infile in infiles]

为了分隔不同的文件(有一系列的行列表)。

liness = [[line.rstrip("\n") for line in open(infile)] for infile in infiles]

上一步有时对于分隔不同文件的信息很重要。 要从lines获取liness,您可以使用:

lines = reduce((lambda a, b: a + b), liness)