Output the result of an input generator and then the result of a translation of the result of the generator

69 Views Asked by At

The following code:

def test(x):
    for i in x:
        yield i
        i = list(i)
        i[1] = "X"
        yield tuple(i)

list(test(it.product(["A", "B"], ["C"])))

Outputs the following list:

[('A', 'C'), ('A', 'X'), ('B', 'C'), ('B', 'X')]

How would I adapt the function such that the input generator results are listed first and then the results of the translation?

So:

[('A', 'C'), ('B', 'C'), ('A', 'X'), ('B', 'X')]
2

There are 2 best solutions below

3
Kelly Bundy On BEST ANSWER
def test(x):
    x = list(x)
    yield from x
    for i in x:
        i = list(i)
        i[1] = "X"
        yield tuple(i)

or

def test(x):
    x1, x2 = it.tee(x)
    yield from x1
    for i in x2:
        i = list(i)
        i[1] = "X"
        yield tuple(i)

Attempt This Online!

3
devpa On

Solution 1:

Inside of test function first, we are converting x to list so we can iterate through x multiple times. In the first loop we are yielding the values in x and in second loop we are inserting the value 'X'.

import itertools as it

def test(x):
    l = list(x)
    for i in l:
        yield i
    for i in l:
        i = list(i)
        i[1] = "X"
        yield tuple(i)

print(list(test(it.product(["A", "B"], ["C"]))))

Output:

[('A', 'C'), ('B', 'C'), ('A', 'X'), ('B', 'X')]

Solution 2:

Here we have used yield from to yield multiple values.

import itertools as it

def test(x):
    vals = list(x)
    yield from vals
    yield from ((v1, "X") for v1, v2 in vals)


print(list(test(it.product(["A", "B"], ["C"]))))