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--) { ... }
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 toimap()to generate consecutive data points. Also, used withizip()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
>>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With