I have a generator, and I'd like to perform a nested loop on it in such a way that the inner loop will start from where the outer loop stands at the moment.
For example, I have a generator that produces the list [1,2,3]
, and my loop should produce: (1,2),(1,3),(2,3)
.
The code I came up with is the following:
from itertools import tee
def my_gen():
my_list = [1, 2, 3]
for x in my_list:
yield x
first_it = my_gen()
while True:
try:
a = next(first_it)
first_it, second_it = tee(first_it)
for b in second_it:
print(a,b)
except StopIteration:
break
This code is cumbersome, not efficient and does not look very pythonic to me. Please notice that I cannot use combinations_with_replacement
because I need an inner loop for processing a specific value from the outer loop.
Any suggestions for a more elegant and pythonic code?