looking for a neat solution to a nested loop problem

Nobody nobody at nowhere.com
Tue Aug 7 11:32:55 EDT 2012


On Mon, 06 Aug 2012 21:02:33 -0700, Larry Hudson wrote:

>>       for i in range(N,N+100):
>>           for j in range(M,M+100):
>>               do_something(i % 100 ,j % 100)
>>
>> Emile
> 
> How about...
> 
> for i in range(100):
>      for j in range(100):
>          do_something((i + N) % 100, (j + M) % 100)

Both of these approaches move the modifications to the sequence into the
body of the loop. It may be preferable to iterate over the desired
sequence directly. E.g.

	for i in ((N + ii) % 100 for ii in xrange(100)):
	    for j in ((M + jj) % 100 for jj in xrange(100)):
	        do_something(i, j)




More information about the Python-list mailing list