looking for a neat solution to a nested loop problem
André Malo
ndparker at gmail.com
Mon Aug 6 14:19:08 EDT 2012
* Tom P wrote:
> consider a nested loop algorithm -
>
> for i in range(100):
> for j in range(100):
> do_something(i,j)
>
> Now, suppose I don't want to use i = 0 and j = 0 as initial values, but
> some other values i = N and j = M, and I want to iterate through all
> 10,000 values in sequence - is there a neat python-like way to this? I
> realize I can do things like use a variable for k in range(10000): and
> then derive values for i and j from k, but I'm wondering if there's
> something less clunky.
you mean:
do_something((i + N) % 100, (j + M) % 100)
?
I'd define my own range function doing exactly that.
def rrange(count, start=0):
for j in xrange(count):
yield (j + start) % count
(untested)
Or use some itertools magic for that. It might be faster.
nd
--
"Umfassendes Werk (auch fuer Umsteiger vom Apache 1.3)"
-- aus einer Rezension
<http://pub.perlig.de/books.html#apache2>
More information about the Python-list
mailing list