Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: C for loop with two variables

Tags:

python

c

I'm new to python. Is there a similar way to write this C for loop with 2 variables in python?

for (i = 0, j = 20; i != j; i++, j--) { ... }
like image 657
Mik Tomiko Avatar asked Jun 17 '26 09:06

Mik Tomiko


2 Answers

Python 2.x

from itertools import izip, count
for i, j in izip(count(0, 1), count(20, -1)):
    if i == j: break
    # do stuff

Python 3.x:

from itertools import count
for i, j in zip(count(0, 1), count(20, -1)):
    if i == j: break
    # do stuff

This uses itertools.count(), an iterator that iterates from a certain starting point indefinitely:

itertools.count(start=0, step=1)

Make an iterator that returns evenly spaced values starting with n. Often used as an argument to imap() to generate consecutive data points. Also, used with izip() to add sequence numbers.

In Python 2.x you have to use izip because Py2K zip tries to create a list of all the results, as opposed to izip which returns an iterator over the results as they are obtained. Unfortunately we are dealing with infinite iterators here so zip won't work... this is probably a good point as to why zip has been changed to perform the role of izip in Py3K (izip no longer exists there).

If you are crazy about being functional you could even do this (but it looks ugly in my opinion since I have grown to hate lambdas):

from itertools import takewhile, izip, count
for i, j in takewhile(lambda x: x[0] != x[1], izip(count(0, 1), count(20, -1))):
    # do stuff
like image 159
jamylak Avatar answered Jun 19 '26 00:06

jamylak


>>> i, j = 0, 10
>>> while i != j:
...     # Your code here:
...     print "i: %d j: %d" % (i, j)
...     i += 1
...     j -= 1
...
...
i: 0 j: 10
i: 1 j: 9
i: 2 j: 8
i: 3 j: 7
i: 4 j: 6

If you wonder why it's common to see >>> and ... in code examples it's because people are using the python interpreter (a shell, if you'd like), or a wrapper around the python interpreter like bpython. I really recommend getting bpython for testing code like this.

like image 22
timss Avatar answered Jun 18 '26 23:06

timss