looking for a neat solution to a nested loop problem

Oscar Benjamin oscar.benjamin at bristol.ac.uk
Mon Aug 6 13:35:40 EDT 2012


On 6 August 2012 18:14, 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)
>
> .. apologies if I didn't make that clear enough.


How about range(N, 100) + range(0, N)?

Example (Python 2.x):

>>> range(3, 10)
[3, 4, 5, 6, 7, 8, 9]
>>> range(0, 3)
[0, 1, 2]
>>> range(3, 10) + range(0, 3)
[3, 4, 5, 6, 7, 8, 9, 0, 1, 2]

In Python 3.x you'd need to do list(range(...)) + list(range(...)) or use
itertools.chain.

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120806/9952766d/attachment.html>


More information about the Python-list mailing list