在读取文件时,我可以使用列表推导来获取每个非空行的顺序位置吗?

时间:2014-03-21 16:47:05

标签: python list-comprehension

我一直在努力创建一个包含行号和行的元组列表,但我只想枚举非空行

这让我得到了我想要的东西

counter = 0
line_list = []
for line in open(file).readlines()
    if line.strip() == '':
        continue
    line_list.append((counter,line.strip()))
    counter +=1

当我这样做时

line_list = [(index,line) for index, line in \
             enumerate(open(file).readlines() if line.strip() != 0]

正如预期的那样(在我想到之后)读取每行的索引进展因此我在读取的每个空白行的数字上都有差距

我也试过

counter = 0
line_list = [(counter,line) for line in open(file).readlines() \
            if line.strip != '' counter +=1]

这给了我一个语法错误

以下是原始文件类型的示例

'Some words are in a line \n'
' maybe another line with more words\n'
'\n'
'\n'
'See the one or more blank lines\n'
'maybe more or less word\n'
'\n'
'\n'
'lots of lines with text\n'

2 个答案:

答案 0 :(得分:3)

枚举非空行:

[(index, line) for index,line in enumerate(l for l in open(file) if l.strip())]

答案 1 :(得分:2)

line_list = list(enumerate(line for line in open(file) if line.strip()))