8

Say I have these 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.

By using cycle with zip as following:

from itertools import cycle
for a,b,c in 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

Though I want my result to be like:

1 a 1
2 b 1
3 c 1
4 d 1
5 a 2
6 b 2
pomo_mondreganto
  • 2,028
  • 2
  • 28
  • 56
Abhijay Ghildyal
  • 4,044
  • 6
  • 33
  • 54

2 Answers2

4

You can use itertools.repeat() to repeat the items of third list based on 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)]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • I also want to add a dList = [3,4] – Abhijay Ghildyal Aug 04 '16 at 13:46
  • @AbhijayGhildyal If you are using `numpy` you should added the tag to you r question and/or mention a proper example. I suggest you ask another question since it might has a completely different answer. And you'd get a proper one. – Mazdak Aug 04 '16 at 13:47
4

You can apply itertools.product on c and b and then restore their original order in the print statement:

>>> 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
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139