Python Multiple FOR Statements (3-fold?)

Asked 2 years ago, Updated 2 years ago, 72 views

first = ['a', 'b', 'c', 'd', 'e' ] 
second = ['x', 'y', 'z' ] 
third = ['apple', 'banana' ] 
N = 10

I'd like to repeat it N times with For Moon using the list above.

I can't think of an answer. "T" If I do it like below, it can be first, but I want to put the rest in.


for i , j in enumerate(first*2):
    i = i + 1
    print(i, j)

ex) I want it to come out like this.

1: a, x, apple 
2: b, y, banana 
3: c, z, apple 
4: d, x, banana
5: e, y, apple 
6: a, z, banana
7: b, x, apple
8: c, y, banana
9: d, z, apple
10: e, x, banana

python for

2022-09-22 15:16

3 Answers

You don't have to triple it. It's enough!

first = ['a', 'b', 'c', 'd', 'e' ] 
second = ['x', 'y', 'z' ] 
third = ['apple', 'banana' ] 
N = 10

for i in range(N) :
    print("%s: %s, %s, %s" % (i + 1, first[i - (i//5)*5], second[i - (i//3)*3], third[i - (i//2)*2]))


2022-09-22 15:16

You can also use itertools.

Please refer to it.

>>> first = ['a', 'b', 'c', 'd', 'e' ]
>>> second = ['x', 'y', 'z' ]
>>> third = ['apple', 'banana' ]
>>> N = 10
>>> from itertools import cycle, islice
>>> for v1, v2, v3 in zip(islice(cycle(first), N), islice(cycle(second), N), islice(cycle(third), N)):
...     ...     print(v1, v2, v3)
... 
a x apple
b y banana
c z apple
d x banana
e y apple
a z banana
b x apple
c y banana
d z apple
e x banana


2022-09-22 15:16

Wow, thank you. :-)

I ended up solving it using a zip, but I think this is a clearer answer!


2022-09-22 15:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.