"for loop" with two variables?

How to include two variables in the same for loop?

 t1 = [a list of integers, strings and lists] t2 = [another list of integers, strings and lists] def f(t): #a function that will read lists "t1" and "t2" and return all elements that are identical for i in range(len(t1)) and for j in range(len(t2)): ... 
+99
python for-loop
Sep 06 '13 at 1:48 on
source share
8 answers

If you need a nested loop effect, use:

 import itertools for i, j in itertools.product(range(x), range(y)): # Stuff... 

If you want to just execute the loop at the same time, use:

 for i, j in zip(range(x), range(y)): # Stuff... 

Note that if x and y do not have the same length, zip will be truncated to the shortest. As @abarnert pointed out, if you don't want to truncate to the shortest list, you can use itertools.zip_longest .

UPDATE

Based on the request "a function that will read the lists" t1 "and" t2 "and returns all identical elements", I do not think the OP wants zip or product . I think they want set :

 def equal_elements(t1, t2): return list(set(t1).intersection(set(t2))) # You could also do # return list(set(t1) & set(t2)) 

The intersection method for set will return all elements common to it and another set (note that if your lists contain different list s, you may need to convert the internal list to tuples first so that they are hashed, otherwise the set call will fail.) . The list function then returns the set to the list.

UPDATE 2

OR, the OP may want items that are identical at the same position in lists. In this case, zip will be most suitable, and the fact that it is truncated to the shortest list is what you would like (since it is impossible for the same element to be in index 9 when one of the lists was only 5 items are long). If this is what you want, go to the following:

 def equal_elements(t1, t2): return [x for x, y in zip(t1, t2) if x == y] 

This will return a list containing only those items that are the same and are in the same position in the lists.

+172
Sep 06 '13 at 1:55
source share
— -

There are two possible questions: how can you iterate over these variables at the same time, or how can you iterate over their combination.

Fortunately, there are simple answers to both questions. In the first case, you want to use zip .

 x = [1, 2, 3] y = [4, 5, 6] for i, j in zip(x, y): print(str(i) + " / " + str(j)) 

will bring

 1 / 4 2 / 5 3 / 6 

Remember that you can put any iteration in zip so you can write your example just as easily, for example:

 for i, j in zip(range(x), range(y)): # do work here. 

In fact, I just realized that this would not work. It will be repeated until a smaller range has elapsed. In this case, it sounds like you want to loop through a combination of loops.

Otherwise, you just need a nested loop.

 for i in x: for j in y: print(str(i) + " / " + str(j)) 

gives you

 1 / 4 1 / 5 1 / 6 2 / 4 2 / 5 ... 

You can also do this as a list comprehension.

 [str(i) + " / " + str(j) for i in range(x) for j in range(y)] 

Hope this helps.

+31
Sep 06 '13 at 2:00
source share

Why can't you use a nested loop?

 for i in range(x): for j in range(y): #code that uses i and j 
+20
Sep 06 '13 at 1:52
source share
 for (i,j) in [(i,j) for i in range(x) for j in range(y)] 

must do it.

+13
Sep 06 '13 at 1:51 on
source share

If you really have an iteration of locking in a range, you can do this in one of several ways:

 for i in range(x): j = i … # or for i, j in enumerate(range(x)): … # or for i, j in ((i,i) for i in range(x)): … 

All of the above is equivalent to for i, j in zip(range(x), range(y)) if x <= y .

If you need a nested loop and you have only two iteratives, just use a nested loop:

 for i in range(x): for i in range(y): … 

If you have more than two iterations, use itertools.product .

Finally, if you need an iteration with locking to x , and then to continue y , you have to decide what other x values ​​should be.

 for i, j in itertools.zip_longest(range(x), range(y), fillvalue=float('nan')): … # or for i in range(min(x,y)): j = i … for i in range(min(x,y), max(x,y)): j = float('nan') … 
+8
Sep 06 '13 at 2:22 on
source share

"Python 3."

Add 2 vars with a for loop using zip and range; Return list.

Note. Will only work to the smallest range.

 >>>a=[g+h for g,h in zip(range(10), range(10))] >>>a >>>[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] 
+6
Jul 04 '17 at 17:29
source share

I think you are looking for nested loops.

Example (based on your edit):

 t1=[1,2,'Hello',(1,2),999,1.23] t2=[1,'Hello',(1,2),999] t3=[] for it1, e1 in enumerate(t1): for it2, e2 in enumerate(t2): if e1==e2: t3.append((it1,it2,e1)) # t3=[(0, 0, 1), (2, 1, 'Hello'), (3, 2, (1, 2)), (4, 3, 999)] 

Which can be reduced to a common understanding:

 [(it1,it2,e1) for it1, e1 in enumerate(t1) for it2, e2 in enumerate(t2) if e1==e2] 

But to find common elements, you can simply do:

 print set(t1) & set(t2) # set([(1, 2), 1, 'Hello', 999]) 

If your list contains objects that do not contain hashed objects (for example, other lists, dicts), use a frozen set:

 from collections import Iterable s1=set(frozenset(e1) if isinstance(e1,Iterable) else e1 for e1 in t1) s2=set(frozenset(e2) if isinstance(e2,Iterable) else e2 for e2 in t2) print s1 & s2 
+3
Sep 06 '13 at 2:26 on
source share

For your use case, it might be easier to use a while .

 t1 = [137, 42] t2 = ["Hello", "world"] i = 0 j = 0 while i < len(t1) and j < len(t2): print t1[i], t2[j] i += 1 j += 1 # 137 Hello # 42 world 

As a warning, this approach will be trimmed to the length of your shortest list.

+3
Apr 28 '18 at 2:57
source share



All Articles