gpt4 book ai didi

python - 如何避免通过python中的if语句多次重复条件?

转载 作者:太空宇宙 更新时间:2023-11-04 09:52:56 25 4
gpt4 key购买 nike

有没有更好的办法避免通过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)

我尝试使用 但它无法正常工作,因为我得到的实体具有不应存储在数据中的条件。

最佳答案

使用内置的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)

关于python - 如何避免通过python中的if语句多次重复条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47016867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com