Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten Sequence With Boolean Expression Generator

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
like image 946
donopj2 Avatar asked Sep 29 '26 11:09

donopj2


1 Answers

(x[0] or x[1] for x in my_data)

or alternatively,

(x or y for x,y in my_data)
like image 195
Amber Avatar answered Oct 01 '26 21:10

Amber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!