检查python中的type == list

时间:2014-10-24 08:23:29

标签: python

我可能在这里有一个大脑放屁,但我真的无法弄清楚我的代码有什么问题:

for key in tmpDict:
    print type(tmpDict[key])
    time.sleep(1)
    if(type(tmpDict[key])==list):
        print 'this is never visible'
        break

输出为<type 'list'>,但if语句永远不会触发。谁能在这里发现我的错误?

5 个答案:

答案 0 :(得分:83)

您应该尝试使用isinstance()

if isinstance(object, (list,)):
       ## DO what you want

在你的情况下

if isinstance(tmpDict[key], (list,)):
      ## DO SOMETHING
编辑:在看到对我的回答的评论后,我想到详细说明。

x = [1,2,3]
if type(x) == list():
    print "This wont work"
if type(x) == list:                  ## one of the way to see if it's list
    print "this will work"           
if type(x) == type(list()):
    print "lets see if this works"
if isinstance(x,(list,)):            ## most preferred way to check if it's list
    print "This should work just fine"
if isinstance(x, list):              ## Nice way to check if it's a list
    print "This should also work just fine"

答案 1 :(得分:68)

您的问题是您已在代码中将list重新定义为变量。这意味着当您执行type(tmpDict[key])==list时,如果返回False,则因为它们不相等。

话虽如此,在测试某事物的类型时,你应该使用isinstance(tmpDict[key], list),这不会避免覆盖list的问题,但是这是一种检查类型的Pythonic方法。

答案 2 :(得分:15)

这似乎对我有用:

>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True

答案 3 :(得分:1)

Python 3.7.7

import typing
if isinstance([1, 2, 3, 4, 5] , typing.List):
    print("It is a list")

答案 4 :(得分:1)

尽管不如isinstance(x, list)那样简单,但也可以使用:

this_is_a_list=[1,2,3]
if type(this_is_a_list) == type([]):
    print("This is a list!")

我有点喜欢它的简单聪明