使循环变得更加惯用

时间:2016-06-26 18:45:17

标签: python

我想让第一个for循环更加pythonic,那么我怎样才能只使用一个变量而不是2?:

    #Split input file into lines using LF as separator
    program_lines1 = input_file.split("\n", "")

    #Delete CR at end of lines if present
    program_lines2 = ""
    for line in program_lines1:
        program_lines2.append(line.replace("\r"))

    #Delete 3rd and last lines of file which are never requested
    del program_lines2[2]
    del program_lines2[-1]

    #Delete all p2 lines
    for line in range(len(program_lines2)):
        program_lines2.remove("p2")

我认为枚举可能是答案的一部分。另外,对于最后一个循环,还有更多的pythonic吗?感谢。

2 个答案:

答案 0 :(得分:3)

如果我理解您的代码:

for line in range(len(program_lines2)):
        program_lines2.remove("p2")

可以替换为

program_lines2 = [line for line in program_lines2 if line != 'p2']

与第一个变量相同的情况 - 代码

for line in program_lines1:
    program_lines2.append(line.replace("\r"))

可以替换为

program_lines1 = [line.replace("\r") for line in program_lines1]

我希望它有所帮助。

答案 1 :(得分:0)

沿着这些方向的东西?采取不使用“for”循环的自由。

with open('filename.txt') as f:
    lines = f.readlines()  # Split file into lines
    lines = list(map(lambda x: x.strip(), lines))  # Clear LF's
    lines = list(filter(lambda x: x != "p2", lines))  # Remove all 'p2'
    lines.pop(2)  # Remove third line
    lines.pop(-1)  # Remove last one