Python - 忽略文件中的行

Dar*_*ick 2 python loops ignore file lines

如何忽略文件中的行?

例:

如果您知道文件中的第一行将以say,a或b开头,其余行以c结尾,那么如何解析文件以便忽略以a或b开头的行,并将结束c的行转换为a嵌套列表?

到目前为止我所拥有的:

fname = raw_input('Enter file name: ')

z = open(fname, 'r')

#I tried this but it converts all lines to a nested list

z_list = [i.strip().split() for i in z]
Run Code Online (Sandbox Code Playgroud)

我猜我需要一个for循环.

for line in z:
    if line[0] == 'a':
        pass
    if line[0] == 'b':
        pass
    if line[-1] == 'c':
        list_1 = [line.strip().split()]
Run Code Online (Sandbox Code Playgroud)

以上是一般的想法,但我是制作死代码的专家!如何渲染它不死?

谢谢,Seafoid.

Nad*_*mli 9

startswith可以使用一串字符串来匹配,所以你可以这样做:

[line.strip().split() for line in z if not line.startswith(('a', 'b'))]
Run Code Online (Sandbox Code Playgroud)

即使a和b不仅仅是字符,单词或句子也是如此.如果可能存在行不以a或b开头而且也不以c结尾的情况,则可以将列表理解扩展到:

[
    line.strip().split()
    for line in z if line.endswith('c') and not line.startswith(('a', 'b'))
]
Run Code Online (Sandbox Code Playgroud)