python中的条件if语句

2024-09-26 22:11:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我不想编写长的“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

但是多重查询不起作用


Tags: and字符串ininfolenif条件lower
3条回答
>>> 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。你应该去掉单引号。你知道吗

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

string_expression = '1 >0 and 10 > 12'
condition = eval(string_expression)
if condition:
   print something
else:
   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

相关问题 更多 >

    热门问题