检查列表是否包含类型?

时间:2022-10-16 19:22:20

What is the fastest way I can check for a certain types existence in a list?

什么是最快的方式,我可以检查在一个列表中的特定类型存在?

I wish I could do the following:

我希望我能做到以下几点:

class Generic(object)
    ... def ...
class SubclassOne(Generic)
    ... def ...
class SubclassOne(Generic)
    ... def ...

thing_one = SubclassOne()
thing_two = SubclassTwo()
list_of_stuff = [thing_one, thing_two]

if list_of_stuff.__contains__(SubclassOne):
    print "Yippie!"

EDIT: Trying to stay within the python 2.7 world. But 3.0 solutions will be ok!

编辑:尝试保持在python 2.7世界中。但是3.0解决方案就可以了!

2 个解决方案

#1


15  

if any(isinstance(x, SubclassOne) for x in list_of_stuff):

如果在list_of_stuff中有x (isinstance(x, subclass1)):

#2


2  

You can use any and isinstance.

您可以使用任何和isinstance。

if any(isinstance(item, SubClassOne) for item in list_of_stuff):
    print "Yippie!"

#1


15  

if any(isinstance(x, SubclassOne) for x in list_of_stuff):

如果在list_of_stuff中有x (isinstance(x, subclass1)):

#2


2  

You can use any and isinstance.

您可以使用任何和isinstance。

if any(isinstance(item, SubClassOne) for item in list_of_stuff):
    print "Yippie!"