如何避免在python中使用if语句多次重复这个条件?

时间:2017-10-30 13:47:33

标签: python python-3.x if-statement logic

有没有更好的方法可以避免if语句多次重复这个条件?

reference

我尝试使用 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) ,但它无法正常工作,因为我得到的实体条件不应该存储在数据中。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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")):