是否有内置函数来确定列表中是否存在类的实例?
目前我是通过理解来做的
>>> class A:
... pass
...
>>> l1=[5,4,3,A(),8]
>>> e=[e for e in l1 if isinstance(e,A)]
最佳答案
Return
True
if any element of the iterable is true. If the iterable is empty, returnFalse
.
>>> class A(object): # subclass object for newstyle class (use them everywhere)
pass
>>> l1=[5,4,3,A(),8]
>>> any(isinstance(x, A) for x in l1)
True
通过使用 generator expresson
(isinstance(x, A) for x in l1)
结合 any
,any
可以短路并在找到第一个 True
值时返回 True
(不像列表理解)。
关于python - 检查实例是否存在于列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16705861/