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
I’m afraid you’ll need to check for
Noneexplicitly, or a tuple like(0, None)or(0, 1)will trip you up:Example: