Co-routines
Alan Kennedy
alanmk at hotmail.com
Thu Jul 17 10:19:11 EDT 2003
thewrights at ozemail.com.au wrote:
> I want to execute these functions in
> "lock-step", so that the output looks like:
>
> 1-1
> 2-2
> 1-2
> 2-2
> 1-3
> 2-3
Have you made a mistake in this output? Should it be this?
1-1
2-1
1-2
2-2
1-3
2-3
If yes, how about this?
#-------------------------
import itertools
def seq(which, iterable):
for i in iterable:
yield "%d-%d" % (which, i)
times = [1,2,3]
seq1 = seq(1, times)
seq2 = seq(2, times)
for v1, v2 in itertools.izip(seq1, seq2):
print v1
print v2
#--------------------------
If you want to generalise the number of iterators, how about this?
#--------------------------
def lizip(iterables):
iterables = map(iter, iterables)
while True:
result = [i.next() for i in iterables]
yield tuple(result)
def seq(which, iterable):
for i in iterable:
yield "%d-%d" % (which, i)
y = [1,2,3] ; max_x = 5
iters = [seq(x, y) for x in range(1, max_x+1)]
for vertslice in lizip(iters):
for v in vertslice:
print v
#--------------------------
Note that these examples don't use "coroutines". Instead they use
python generators, which are classified as "semi-coroutines".
--
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan: http://xhaus.com/mailto/alan
More information about the Python-list
mailing list