Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python,如何检查'if或'statement'中返回'True'的对象?_Python_List_Select_If Statement - Fatal编程技术网

使用Python,如何检查'if或'statement'中返回'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上迭代。创建一个类似这样

我不想遍历列表中的两个对象,只想遍历返回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上迭代。

创建一个类似这样的生成器表达式,并为
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()):
    ...