Avoiding Duplicate Function call in List Comprehension in Python -
i iterate through each file, trim whitespace each line, , delete line if returned string empty. there way avoid duplicating .strip() call in list comprehension below? it's not performance-critical feels wrong.
sub main(): fname = "foo.txt" lns = [] open(fname, 'r') file: lns = file.readlines() newlns = [i.strip() + "\n" in lns if i.strip()] #i want following, doesn't work: #newlns = [y + "\n" in lns if i.strip() y] open("out.txt", 'w') file: file.writelines(newlns)
you can use nested list comprehension (well, generator expression in case avoid building list):
newlns = [i + "\n" in (line.strip() ln in lns) if i] in fact shouldn't bother read file first, put in there too: iterating on file yields lines.
with open(fname, 'r') file: newlns = [i + "\n" in (line.strip() ln in file) if i]
Comments
Post a Comment