检查列表是否包含类型?

时间:2015-09-21 22:57:42

标签: python

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

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

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!"
编辑:试图保持在Python 2.7世界范围内。但3.0解决方案就可以了!

2 个答案:

答案 0 :(得分:17)

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

答案 1 :(得分:2)

您可以使用anyisinstance

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