python中的条件if语句

时间:2016-05-20 00:53:48

标签: python python-2.7

我想将其存储在某个变量中,然后将其传递给'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

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

3 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:1)

由于性能,安全性和维护问题,我强烈建议在生产代码中避免这种情况,但您可以使用eval将字符串转换为实际的bool值:

string_expression = '1 >0 and 10 > 12'
condition = eval(string_expression)
if condition:
   print something
else:
   do something

答案 2 :(得分:0)

>>> 1 > 0 and 10 > 12
False
>>> '1 > 0 and 10 > 12'
'1 > 0 and 10 > 12'
>>> stringtest = '1 > 0 and 10 > 12'
>>> print(stringtest)
1 > 0 and 10 > 12
>>> if stringtest:
...     print("OK")
... 
OK
>>> 1 > 0 and 10 < 12
True
>>> booleantest = 1 > 0 and 10 < 12
>>> print(booleantest)
True
>>>

字符串类型为True。你应该删掉单引号。