Python zip loop over multiple lists

Let's say I have three lists:

aList = [1,2,3,4,5,6]
bList = ['a','b','c','d']
cList = [1,2]

and I want to iterate over them using zip.

Using a loop with the zipfollowing:

from itertools import cycle
for a,b,c zip(aList, cycle(bList), cycle(cList)):
    print a,b,c

I get the result as:

1 a 1
2 b 2
3 c 1
4 d 2
5 a 1
6 b 2

Although I want my result to be like this:

1 a 1
2 b 1
3 c 1
4 d 1
5 a 2
6 b 2
+4
source share
2 answers

You can use itertools.repeat()to repeat elements of the third list based on the second list:

>>> from itertools import repeat, chain
>>> 
>>> zip(aList,cycle(bList), chain.from_iterable(zip(*repeat(cList, len(bList)))))
[(1, 'a', 1),
 (2, 'b', 1),
 (3, 'c', 1),
 (4, 'd', 1),
 (5, 'a', 2),
 (6, 'b', 2)]
+2
source

You can apply itertools.productto cand b, and then restore the original order in the statement print:

>>> from itertools import product, cycle
>>>
>>> for a, b_c in zip(aList, cycle(product(cList, bList))):
...     print a, b_c[1], b_c[0]
...
1 a 1
2 b 1
3 c 1
4 d 1
5 a 2
6 b 2
+2
source

Source: https://habr.com/ru/post/1650163/


All Articles