I am looking for a generator that will flatten a sequence of tuples based on a Boolean expression. My data looks like this:
my_data = ((3, 4), (None, 4), (5, 8), (None, 1), (None, 9)...)
What I'd like to do is to flatten this into a one dimensional generator of numbers where I take the first item in each tuple if it is not None, otherwise take the second item. My result would yield the following sequence:
3, 4, 5, 1, 9...
I am thinking the easiest way to do this would be to use a Boolean expression with short circuiting, but I can't seem to compose a proper generator. I realize I could define a generator function and this would be fairly straightforward, but I'm curious if this can be done with a comprehension?
My attempt:
(x or y for subitem in my_data for x, y in subitem)
Traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
TypeError: 'int' object is not iterable
(x[0] or x[1] for x in my_data)
or alternatively,
(x or y for x,y in my_data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With