Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

skip item in list "for loop"

5 views
Skip to first unread message

Jacob Rael

unread,
Apr 14, 2006, 2:09:32 PM4/14/06
to
I am new to python and I love it. I am hacking a file. I want to not
print a line if it contains the word 'pmos4_highv'. I also don't want
to print the next line. The following code works but it "smells bad"
and just doesn't look right. I was reading about generators. If I was
using one, I could do a .next() after the match and get rid of the
flags. Any suggestions how I can improve this?


inPmos = False

inFile = sys.stdin
fileList = inFile.readlines()

for line in fileList:
line = line.rstrip()
# Remove PMOS definitions - typically two lines. Screwed if only
one and last inst.
if inPmos:
inPmos = False
continue
if 'pmos4_highv' in line:
inPmos = True
continue


jr

Diez B. Roggisch

unread,
Apr 14, 2006, 2:33:50 PM4/14/06
to
Jacob Rael schrieb:

> I am new to python and I love it. I am hacking a file. I want to not
> print a line if it contains the word 'pmos4_highv'. I also don't want
> to print the next line. The following code works but it "smells bad"
> and just doesn't look right. I was reading about generators. If I was
> using one, I could do a .next() after the match and get rid of the
> flags. Any suggestions how I can improve this?

A generator certainly would be handy:

def read_lines(inFile):
fg = iter(inFile)
for line in fg:
if "pmos4_highv" in line:
fg.next()
else:
yield line

lines = """a
b
c
d
pmos4_highv
no no!
e
f
g""".split("\n")


for line in read_lines(lines):
print line


Diez

Felipe Almeida Lessa

unread,
Apr 14, 2006, 2:40:08 PM4/14/06
to Diez B. Roggisch, pytho...@python.org
Em Sex, 2006-04-14 às 20:33 +0200, Diez B. Roggisch escreveu:
> def read_lines(inFile):
> fg = iter(inFile)
> for line in fg:
> if "pmos4_highv" in line:
> fg.next()
> else:
> yield line

Just be aware that the "fb.next()" line can raise an StopIteration
exception that would otherwise be caught by the for loop. If you have
any resources that need to be cleaned up, try...finally is you friend.

--
Felipe.

Diez B. Roggisch

unread,
Apr 14, 2006, 4:57:36 PM4/14/06
to
Felipe Almeida Lessa schrieb:

Actually I did that on purpose - as the StopIteration would simply end
the generator. Any clean-up - well, if that was the scope of the
generator on could add it of course, but I'd do that on the same level
the file has been opened.

Regards,

Diez

Jacob Rael

unread,
Apr 14, 2006, 11:27:48 PM4/14/06
to
Thanks for the suggestions.
The solution I liked most was to prevent the lines from appearing in
the first place!!

0 new messages