2015-09-21 225 views
5

什么是我可以检查列表中某种类型存在的最快方法?检查列表是否包含类型?

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

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!" 

编辑:想留蟒蛇2.7世界中。但3.0解决方案将可以!

回答

10

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

+0

任何!!!!真棒:-)我只用all()找到了不相关的解决方案。谢谢! – visc

2

您可以使用anyisinstance

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