简体   繁体   中英

Simplifying a list comprehension

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM