2016-05-20 8 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 

しかし、その複数の問合せは、単なる文字列を削除し、変数に条件を保存

+1

式の結果を ' (1> 0)と(10> 12) 'はブール値なので、変数に格納してください。私。あなたはほとんどそこにいるだけで、式を文字列に変換しないでください。 –

+0

提案に感謝し、条件がブール値を使用するかどうかわかりませんでした – Paul85

答えて

1

私は非常に起因するパフォーマンス、セキュリティやメンテナンスの問題に、生産コードでこれを避けることをお勧めしますが、実際のbool値にあなたの文字列を変換するために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 
>>> 

文字列型はTrueです。一重引用符を削除する必要があります。