python中的条件if语句

Pau*_*l85 1 python python-2.7

我想将其存储在某个变量中,然后将其传递给'if'条件,而不是写出长'if'语句.例如:

tempvar = '1 >0 and 10 > 12'
if tempvar:
   print something
else:
     do something
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

但是那个多重查询不起作用

Pyt*_*sta 6

只需删除字符串并将条件存储在变量中.

>>> condition = 1 > 0 and 10 > 12
>>> if condition:
...    print("condition is true")
... else:
...    print("condition is false")
...
condition is false
Run Code Online (Sandbox Code Playgroud)

您甚至可以使用(例如)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
Run Code Online (Sandbox Code Playgroud)