2016-05-20 78 views
1

我不想編寫長的'if'語句,而是將它存儲在某個變量中,然後將其傳遞給'if'條件。 例如:Python中的條件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 

但是multiquery不工作

+1

表達式'的結果(1> 0)和(10> 12)'是一個布爾值,所以只需將它存儲在一個變量中。即你幾乎在那裏,只是不要把表達式轉換成一個字符串(無論出於何種原因)。 –

+0

感謝您的建議,我不知道如果條件使用布爾值 – Paul85

回答

1

我會強烈建議避免這種在生產代碼,由於性能,安全性和維護問題,但你可以使用eval你的字符串轉換爲實際的布爾值:

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

剛落,串並存儲條件變量。

>>> condition = 1 > 0 and 10 > 12 
>>> if condition: 
... print("condition is true") 
... else: 
... print("condition is false") 
... 
condition is false 

你甚至可以存儲與(例如)拉姆達的條件比較複雜

下面是使用拉姆達與一些更復雜的隨便舉個例子

(雖然使用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 
+0

謝謝,它真的很棒。但是我已經更新了我的問題,並且這個解決方案仍然不適合我的情況 – Paul85

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

string類型是真。你應該放棄單引號。