itertools.count() as built-in
John Machin
sjmachin at lexicon.net
Sun May 28 21:36:40 EDT 2006
On 29/05/2006 9:50 AM, jantod at gmail.com wrote:
> I have a project of around 6000 lines where I used count() 20 times. It
> has 14 modules, 10 of which I needed an explicit import.
>
> Many of the usages are of the form:
>
> for item, n in zip(items, count(N)):
> dostuff
>
> Around half of these are due to using pylab.subplot(x,y.n), which
> requires values for n>=1. So I want N=1. The enumerate builtin starts
> from 0.
Call me a Luddite if you will, but I'd suggest that instead of
for item, n in zip(items, count(N)):
dostuff(item, n)
you try
(1)
for n, item in enumerate(items):
dostuff(item, n+N)
or (2)
n = N-1
for item in items:
n += 1
dostuff(item, n)
> I also write out textual reports that start with n=1.
>
> I also have things like
> for n, component, rotations in zip(count(),
> sorted(tools.component_files().keys()), all_symbol_rotations)
> where the enumerate version just looks even more confusing and easy to
> mess up
> for n, component, rotations in
> enumerate(sorted(tools.component_files().keys()), all_symbol_rotations)
As enumerate takes only 1 argument, I presume that is the messed-up version.
Yes, the correct version is a pain:
for n, (component, rotations) in enumerate(zip(yadda1, yadda2)):
Perhaps you could use something like this:
>>> def zipwithcount(N, *args):
... for x, guff in enumerate(zip(*args)):
... yield guff + (x + N,)
...
>>> list(zipwithcount(666, 'abc', 'xyz'))
[('a', 'x', 666), ('b', 'y', 667), ('c', 'z', 668)]
>>>
Cheers,
John
More information about the Python-list
mailing list