I want to loop this format using python
Question:
I have 3 lists
a = ["1", "2", "3", "4", "5", "6"]
b = ['a', 'b', 'c']
c = ["13", "14"]
and
the format is:
1 3 a
2 13 b
3 13 c
4 14 a
5 14 b
6 14 c
How do I get the above format?
Answers:
Below Code will print the required sequence with all characters in new line.
for i in c:
for j in b:
for k in a:
print(k,i,j,sep='n')
You can use itertools.cycle
to get the list b
to cycle round and have an adapter with itertools.repeat
to get c
to repeat its items:
from itertools import repeat, cycle
def repeat_elements(iterable, repeat_count):
for element in cycle(iterable):
yield from repeat(element, repeat_count)
a = ["1", "2", "3", "4", "5", "6"]
b = ['a', 'b', 'c']
c = ["13", "14"]
for x,y,z in zip(a, cycle(b), repeat_elements(c, 3)):
print(x,z,y)
Output as requested
Note that this code relies on zip
stopping the iteration when a
has run out of elements. Both cycle
and the adapter repeat_elements
are going to loop endlessly.
I have 3 lists
a = ["1", "2", "3", "4", "5", "6"]
b = ['a', 'b', 'c']
c = ["13", "14"]
and
the format is:
1 3 a
2 13 b
3 13 c
4 14 a
5 14 b
6 14 c
How do I get the above format?
Below Code will print the required sequence with all characters in new line.
for i in c:
for j in b:
for k in a:
print(k,i,j,sep='n')
You can use itertools.cycle
to get the list b
to cycle round and have an adapter with itertools.repeat
to get c
to repeat its items:
from itertools import repeat, cycle
def repeat_elements(iterable, repeat_count):
for element in cycle(iterable):
yield from repeat(element, repeat_count)
a = ["1", "2", "3", "4", "5", "6"]
b = ['a', 'b', 'c']
c = ["13", "14"]
for x,y,z in zip(a, cycle(b), repeat_elements(c, 3)):
print(x,z,y)
Output as requested
Note that this code relies on zip
stopping the iteration when a
has run out of elements. Both cycle
and the adapter repeat_elements
are going to loop endlessly.