Ren
Ren

Reputation: 2946

What can I do when there are two variables in a for loop?

Here are some C code:

    void func(int s,int t)
    {
      int i,j;
      int array[10][10];
      for(i=s,j=t;i>0 && j>0;i--,j--)
        array[i][j]=5;
    }

How can I do that in Python?

Upvotes: 0

Views: 47

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122032

In general, you could do something like:

for i, j in zip(range(3), range(5, 8)):
    ...

where:

>>> range(3)
[0, 1, 2]
>>> range(5, 8)
[5, 6, 7]
>>> zip(range(3), range(5, 8))
[(0, 5), (1, 6), (2, 7)]

See the documentation on zip and range. If you're using Python 2.x and there will be lots of values, using xrange and itertools.izip could be more efficient.

Upvotes: 4

Related Questions