Picking a subset - three ways to filter
In the Using stacked generator expressions recipe, we wrote a generator function that excluded some rows from a set of data. We defined a function like this:
def skip_header_date(rows): for row in rows: if row[0] == 'date': continue yield row
When the condition is true
—row[0]
is date
—the continue
statement will skip the rest of the statements in the body of the for
statement. In this case, there's only a single statement, yield row
.
There are two conditions:
row[0] == 'date'
: Theyield
statement is skipped; the row is rejected from further processingrow[0] != 'date'
: Theyield
statement means that the row will be passed on to the function or statement that's consuming the data
At four lines of code, this seems long-winded. The for...if...yield
pattern is clearly boilerplate, and only the condition is really material in this kind of construct.
Can we express this more succinctly...