dpetican
dpetican

Reputation: 831

Making for loop more idiomatic

I want to make the first for loop more pythonic, so how can I use only one variable instead of 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")

I'm thinking enumerate might be part of the answer. Also, is there anyhting more pythonic for the last for loop?. Thanks.

Upvotes: 0

Views: 86

Answers (2)

Nico Villanueva
Nico Villanueva

Reputation: 894

Something along these lines? Took the liberty of not using "for" loops whatsoever.

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

Upvotes: 0

Absolut
Absolut

Reputation: 1310

If i understand you code:

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

can be replaced with

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

Same situation with first variable - code

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

can be replaced with

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

I hope it helps.

Upvotes: 3

Related Questions