python - 检查实例是否存在于列表中

标签 python list

是否有内置函数来确定列表中是否存在类的实例?
目前我是通过理解来做的

>>> class A:
...     pass
...     
>>> l1=[5,4,3,A(),8]
>>> e=[e for e in l1 if isinstance(e,A)]

最佳答案

any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False.

>>> 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)

结合 anyany 可以短路并在找到第一个 True 值时返回 True (不像列表理解)。

关于python - 检查实例是否存在于列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16705861/

相关文章:

python - 如何在基于类的通用 View 中设置 cookie

python - python 中搜索字符串和字符串列表之间最高百分比 Levenshtein 距离的最快方法是什么?

java - Iterator.hasNext() 似乎不会对列表中的最后一项返回 false

python - 使用 itertools 在 python 中列出列表(仅移动 2 个项目,排列)

javascript - 卡住 jQuery 列表上的滚动,同时调整列表顶部的列表元素的大小

python - NumPy - 什么是广播?

python - 多处理和 dill 可以一起做什么?

python - Pandas DataFrame 将除 0 以外的每个值替换为 1

java - 当日历selenium java上出现2个日期时,如何选择可点击的日期?

python - 如何将嵌套字典转换为列表字符串