[英]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?另外,是否可以传入一个列表或一些包含 1、9 等的 object?
使用一组:
if {1,9}.intersection(sh1.row_values(row))
You can add a function inside list comprehension.您可以在列表理解中添加 function。 I'm adding generic code here.
我在这里添加通用代码。 Can modify as required.
可以根据需要修改。
Example例子
def filter_foo(j, x):
if j == x:
return True
else:
return False
lst = [i for i in src_lst if filter_foo(i, x)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.