Search code examples
pythonconditional-statementslist-comprehension

Or condition in list comprehension


Is there a way to accomplish the below in a more concise way? If i have a lot of values the for in condition my script will become very unreadable.

Current Code

import xlrd  
filename = r'H:\Book1.xls'
wb = xlrd.open_workbook(filename)
sh1 = wb.sheet_by_index(0)
data = [sh1.row_values(row) for row in range(sh1.nrows) if 1 in sh1.row_values(row) or 9 in sh1.row_values(row) ]
print(data)

Code Result

[[1.0, 2.0, 3.0, '', 4.0, '', 6.0], ['', '', '', '', 9.0, '', '']]

Desired Syntax

data = [sh1.row_values(row) for row in range(sh1.nrows) if 1,9 in sh1.row_values(row)]

Also, would it be possible to pass in a list or some object that contains 1, 9, etc?


Solution

  • Use a set:

    if {1,9}.intersection(sh1.row_values(row))