an enumerate question

skip at pobox.com skip at pobox.com
Mon Mar 19 22:16:35 EDT 2007


    eight> thanks for replying. sorry i make clear again.
    eight> say
    eight> for n,l in enumerate(open("file")):
    eight>    print n,l # this prints current line
    eight>    print next line in this current iteration of the loop.

Off the top of my head, I'd try something like:

    class TwoLiner:
        def __init__(self, f):
            self.f = f

        def __iter__(self):
            return self

        def next(self):
            line1 = self.f.next()
            line2 = self.f.next()
            return (line1, line2)

    for n, (line1, line2) in enumerate(TwoLiner(open("file")):
        print n, line1
        print line2

Note that this has and end-of-file problem.  When your file contains an odd
number of lines, at the end of the file TwoLiner.next will raise
StopIteration during the second self.f.next() call and you'll lose the last
line of the file.  You can work around it with something like this:

        def next(self):
            line1 = self.f.next()
            try:
                line2 = self.f.next()
            except StopIteration:
                line2 = None
            return (line1, line2)

then when using it you have to test line2 for None:

    for n, (line1, line2) in enumerate(TwoLiner(open("file")):
        print n, line1
        if line2 is not None:
            print line2

Skip



More information about the Python-list mailing list