2015-09-21 220 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!"