我不想写很长的“if”语句,而是想将其存储在某个变量中,然后将其传递给“if”条件。 例如:
tempvar = '1 >0 and 10 > 12'
if tempvar:
print something
else:
do something
在 python 中可以吗?
感谢您的建议,但我的问题是我无法弄清楚的其他问题。 我正在文本文件中进行多字符串搜索,并尝试将多字符串转换为一个条件:
allspeciesfileter=['Homo sapiens', 'Mus musculus', 'Rattus norvegicus' ,'Sus scrofa']
multiequerylist=[]
if len(userprotein)> 0:
multiequerylist.append("(str("+ "'"+userprotein+ "'"+")).lower() in (info[2].strip()).lower()")
if len(useruniprotkb) >0:
multiequerylist.append("(str("+ "'"+useruniprotkb+ "'"+")).lower() in (info[3].strip()).lower()")
if len(userpepid) >0:
multiequerylist.append("(str("+ "'"+userpepid+ "'"+")).lower() in (info[0].strip()).lower()")
if len(userpepseq) >0:
multiequerylist.append("(str("+ "'"+userpepseq+ "'"+")).lower() in (info[1].strip()).lower()")
multiequery =' and '.join(multiequerylist)
for line in pepfile:
data=line.strip()
info= data.split('\t')
tempvar = bool (multiquery)
if tempvar:
do something
但是那个多查询不起作用
请您参考如下方法:
只需删除字符串并将条件存储在变量中。
>>> condition = 1 > 0 and 10 > 12
>>> if condition:
... print("condition is true")
... else:
... print("condition is false")
...
condition is false
您甚至可以使用(例如)lambda 存储更复杂的条件
这是使用 lambda 的随机示例,稍微复杂一些
(虽然使用 BS 来解析这有点矫枉过正)
>>> from bs4 import BeautifulSoup
>>> html = "<a href='#' class='a-bad-class another-class another-class-again'>a link</a>"
>>> bad_classes = ['a-bad-class', 'another-bad-class']
>>> condition = lambda x: not any(c in bad_classes for c in x['class'])
>>> soup = BeautifulSoup(html, "html.parser")
>>> anchor = soup.find("a")
>>> if anchor.has_attr('class') and condition(anchor):
... print("No bad classes")
... else:
... print("Condition failed")
Condition failed
