Python: C for loop with two variables -


i'm new python. there similar way write c loop 2 variables in python?

for (i = 0, j = 20; != j; i++, j--) { ... } 

python 2.x

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

python 3.x:

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

this uses itertools.count(), iterator iterates starting point indefinitely:

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

make iterator returns evenly spaced values starting n. used argument imap() generate consecutive data points. also, used izip() add sequence numbers.

in python 2.x have use izip because py2k zip tries create list of results, opposed izip returns iterator on results obtained. unfortunately dealing infinite iterators here zip won't work... point why zip has been changed perform role of izip in py3k (izip no longer exists there).

if crazy being functional (but looks ugly in opinion since have grown hate lambdas):

from itertools import takewhile, izip, count i, j in takewhile(lambda x: x[0] != x[1], izip(count(0, 1), count(20, -1))):     # stuff 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -