Skip to main content
 首页 » 编程设计

python之简化列表理解

2025年05月04日15dflying

我怎样才能更简洁地写出下面的内容?

    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)))) 

(sheet.cell(n, i).value for i in (18, 19, 20)) 是一个 generator expression替换 list(...) 部分。您可以将元组 (18, 19, 20) 替换为范围或其他内容。

过滤器(无,可迭代) is equivalent to (x for x in iterable if x)。 (在 Python 2.x 中,您可能希望使用 itertools.ifilter 代替。)


另请注意,您可以使用

创建列表
[sheet.cell(n,18).value, sheet.cell(n,19).value, sheet.cell(n,20).value] 

而不是更长的 list((sheet.cell(n,18).value, …))。