Python: Loops for simultaneous operation, Two or possibly more? -


this question closely relates how run 2 python loops concurrently?

i'll put in clearer manner: questioner asks in above link, like

for in [1,2,3], j in [3,2,1]:     print i,j     cmp(i,j) #do_something(i,j) 

but

l1: in [1,2,3] , j in [3,2,1]: doesnt work

q1. amusing happened here:

    in [1,2,3], j in [3,2,1]:     print i,j   [1, 2, 3] 0 false 0 

q2. how make l1 work?

not multithreading or parallelism really. (it's 2 concurrent tasks not loop inside loop) , compare result of two.

here lists numbers. case not numbers:

for in f_iterate1() , j in f_iterate2(): 

update: abarnert below right, had j defined somewhere. is:

>>> in [1,2,3], j in [3,2,1]:     print i,j    traceback (most recent call last):   file "<pyshell#142>", line 1, in <module>     in [1,2,3], j in [3,2,1]: nameerror: name 'j' not defined 

and not looking zip 2 iteration functions! process them simultaneously in loop situation. , question still remains how can achieved in python.

update #2: solved same length lists

>>> def a(num):     x in num:         yield x   >>> n1=[1,2,3,4] >>> n2=[3,4,5,6] >>> x1=a(n1) >>> x2=a(n2) >>> i,j in zip(x1,x2):     print i,j   1 3 2 4 3 5 4 6 >>>  

[solved]

q3. if n3=[3,4,5,6,7,8,78,34] greater both n1,n2. zip wont work here.something izip_longest? izip_longest works enough.

it's hard understand you're asking, think want zip:

for i, j in zip([1,2,3], [3,2,1]):     print i, j  i, j in zip(f_iterate1(), f_iterate2()):     print i, j 

and on…

this doesn't concurrently term used, 1 thing @ time, 1 thing "iterate on 2 sequences in lock-step".


note extends in obvious way 3 or more lists:

for i, j, k in zip([1,2,3], [3,2,1], [13, 22, 31]):     print i, j, k 

(if don't know how many lists have, see comments.)


in case you're wondering what's going on this:

for in [1,2,3], j in [3,2,1]:     print i,j 

try this:

print [1,2,3], j in [3,2,1] 

if you've defined j somewhere, print either [1, 2, 3] false or [1, 2, 3] true. otherwise, you'll nameerror. that's because you're creating tuple of 2 values, first being list [1,2,3], , second being result of expression j in [3,2,1].

so:

j=0 in [1,2,3], j in [3,2 1]:     print i, j 

… equivalent to:

j=0 in ([1,2,3], false):     print i, 0 

… print:

[1, 2, 3] 0 false 0 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -