2017-10-30 7 views
1

if文で条件を何度も繰り返さないようにする良い方法はありますか?Pythonでif文を何度も繰り返すのを避ける方法は?

for entity in entities: 
     if (entity.entity_id.startswith('sensor') and "sourcenodeid" not in entity.entity_id and "interval" not in entity.entity_id and "previous" not in entity.entity_id and "exporting" not in entity.entity_id and "management" not in entity.entity_id and "yr" not in entity.entity_id and "alarm" not in entity.entity_id): 
      data = remote.get_state(api, entity.entity_id) 
      #print(data) 

私はorと試みたが、私は、データに格納すべきではない状態で実体を得たので、それが正しく動作しません。

答えて

1

allのジェネレータ式を使用します。

if entity.entity_id.startswith('sensor') and all(elem not in entity.entity_id for elem in ("sourcenodeid", "interval", "previous", "exporting", "management", "yr", "alarm")): 
+0

ありがとうございました。すべてのジェネレータの表現は毎回宝くじより良いです – AhmyOhlin

3

ビルトインallを使用します。

tup = ("sourcenodeid", "interval", "previous", "exporting", "management" , "yr", "alarm") 
for entity in entities: 
    if entity.entity_id.startswith('sensor') and \ 
     all(x not in entity.entity_id for x in tup)): 
     data = remote.get_state(api, entity.entity_id) 
+0

それは@ダニエルのかなり同じソリューションです。違いは、前にtupelを定義することだけです。プログラムをより理解しやすくします。 – AhmyOhlin

関連する問題