Loops and things
Tim Chase
python.list at tim.thechases.com
Fri Dec 14 10:57:29 EST 2007
> I was wondering how and if it's possible to write a loop in python
> which updates two or more variables at a time. For instance, something
> like this in C:
>
> for (i = 0, j = 10; i < 10 && j < 20; i++, j++) {
> printf("i = %d, j = %d\n", i, j);
> }
Well, yes it can be done, but depending on your use-case, there
might be smarter ways of doing it:
for (i,j) in map(lambda i: (i, i+10), xrange(10)):
print "i = %d, j = %d" % (i,j)
or just
for pair in map(lambda i: (i, i+10), xrange(10)):
print "i = %d, j = %d" % pair
or even just
for i in xrange(10):
print "i = %d, j = %d" % (i,i+10)
If you need varying sources, you can use zip() to do something like
for (i,j) in zip(xrange(10), myiter(72)):
print "i = %d, j = %d" % (i,j)
where myiter() produces the random sequence of items for j.
If they produce voluminous output, you can import itertools and
use izip and imap instead.
Or, if you want a more literal mapping:
i, j = 0, 10
while i < 10 && j < 20:
print "i = %d, j = %d" % (i,j)
i += 1
j += 1
Pick your poison.
> So that I would get:
>
> i = 0, j = 0
> i = 1, j = 1
> i = 2, j = 2
> ...
> ...
I'm not sure how, with your code, "j" could be (0,1,2,...)
instead of (10,11,12,...).
-tkc
More information about the Python-list
mailing list