使用Python,如何检查'if或'statement'中返回'True'的对象?
我不想遍历列表中的两个对象,只想遍历返回True的对象。 我好像想不出来使用Python,如何检查'if或'statement'中返回'True'的对象?,python,list,select,if-statement,Python,List,Select,If Statement,我不想遍历列表中的两个对象,只想遍历返回True的对象。 我好像想不出来 谢谢如果声明: if mo.exists() or ao.exists(): for d in [mo,ao] 试试这个 if mo.exists(): for d in mo: #do stuff elif ao.exists(): for d in ao: #do other stuff 捕获res列表中的所有True并在res上迭代。创建一个类似这样
谢谢如果声明:
if mo.exists() or ao.exists():
for d in [mo,ao]
试试这个
if mo.exists():
for d in mo:
#do stuff
elif ao.exists():
for d in ao:
#do other stuff
捕获res列表中的所有True并在res上迭代。创建一个类似这样的生成器表达式,并为
exists()
调用过滤返回True
的对象
res=[d for d in [mo,ao] if d.exists()]
for r in res:
如果这两个都是真的呢?“thefourtheye”回答了我们两个。谢谢你,朋友,我今天学到了一些东西:)如果不是mo应该是
。存在():
如果两者都存在怎么办?如果exists()的计算成本相当高(如在数据库中查找),该怎么办?最好使用另一种解决方案,即每个对象只调用exists()一次。另一个想法是:对于过滤器中的项(lambda x:x.exists(),(mo,ao))
@TimPietzcker确实如此,但Python社区喜欢远离filter
和lambda
函数,
res=[d for d in [mo,ao] if d.exists()]
for r in res:
for item in (obj for obj in (mo, ao) if obj.exists()):
...