looking for a neat solution to a nested loop problem

Grant Edwards invalid at invalid.invalid
Mon Aug 6 14:29:31 EDT 2012


On 2012-08-06, Grant Edwards <invalid at invalid.invalid> wrote:
> On 2012-08-06, Tom P <werotizy at freent.dd> wrote:
>> On 08/06/2012 06:18 PM, Nobody wrote:
>>> On Mon, 06 Aug 2012 17:52:31 +0200, 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?
>>>
>>> 	for i in range(N,N+100):
>>> 	    for j in range(M,M+100):
>>> 	        do_something(i,j)
>>>
>>> Or did you mean something else?
>>
>> no, I meant something else ..
>>
>>    j runs through range(M, 100) and then range(0,M), and i runs through 
>> range(N,100) and then range(0,N)
>
> In 2.x:
>
>     for i in range(M,100)+range(0,M):
>         for j in range(N,100)+range(0,N):
>             do_something(i,j)
>
> Dunno if that still works in 3.x.  I doubt it, since I think in 3.x
> range returns an iterator, not?

Indeed it doesn't work in 3.x, but this does:

    from itertools import chain

    for i in chain(range(M,100),range(0,M)):
        for j in chain(range(N,100),range(0,N)):
            do_something(i,j)


-- 
Grant Edwards               grant.b.edwards        Yow! People humiliating
                                  at               a salami!
                              gmail.com            



More information about the Python-list mailing list