Question on loops
Sean Ross
sross at connectmail.carleton.ca
Sun Mar 7 21:35:03 EST 2004
"Daniel H Neilson" <google at neilson.sent.com> wrote in message
news:e0bff448.0403071748.352848e2 at posting.google.com...
[snip]
> I need to take
> another action every 100 lines. Currently I am using something to the
> effect of:
>
> i = 0
> for line in file:
> if i == 100:
> action
> i = 0
> else:
> i += 1
> process(line)
>
> But this doesn't feel like a very python-esque solution to me, and is
> not very elegant in any case. What would be a better way to do it?
[snip]
Hi
If you're using Python 2.3+ you can use enumerate() and a little
modulo arithmetic:
for index, line in enumerate(file):
if (index+1)%100 == 0:
action
process(line)
enumerate() generates (index, value) pairs for an iterable (in this case,
your file), so you don't need to maintain your own counter (i).
The modulo arithmetic ((index+1)%100 == 0) lets you perform
your action every 100 lines [*] (and avoids performing your action
on the first iteration when index == 0).
HTH,
Sean
[*]
In your original code, you're actually doing your action every 101
lines - notice:
len([0,1,2,3,4, ..., 98,99]) == 100
len([0,1,2,3,4, ..., 98,99,100]) == 101
More information about the Python-list
mailing list