How would I write the following more concisely?
genres = ','.join([item for item in list((sheet.cell(n,18).value,
sheet.cell(n,19).value, sheet.cell(n,20).value)) if item])
How would I write the following more concisely?
genres = ','.join([item for item in list((sheet.cell(n,18).value,
sheet.cell(n,19).value, sheet.cell(n,20).value)) if item])
','.join(filter(None, (sheet.cell(n, i).value for i in (18, 19, 20))))
The (sheet.cell(n, i).value for i in (18, 19, 20))
is a generator expression replacing the list(…)
part. You may replace the tuple (18, 19, 20)
with a range or something else.
The filter(None, iterable)
is equivalent to (x for x in iterable if x)
. (In Python 2.x you may want to use itertools.ifilter instead.)
Note also that, you can create a list using
[sheet.cell(n,18).value, sheet.cell(n,19).value, sheet.cell(n,20).value]
instead of the longer list((sheet.cell(n,18).value, …))
.
On two lines. Readability trumps conciseness.
Your list comprehension is also unnecessary, a genexp will do fine.
genre_values = (sheet.cell(n, i).value for i in xrange(18, 21))
genres = ", ".join(value for value in genre_cells if value)