检查类型==列表在python中

问题:检查类型==列表在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语句从不触发。有人可以在这里发现我的错误吗?

I may be having a brain fart here, but I really can’t figure out what’s wrong with my code:

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

the output is <type 'list'> but the if statement never triggers. Can anyone spot my error here?


回答 0

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

话虽如此,您应该isinstance(tmpDict[key], list)在测试某种类型时使用它,这不会避免覆盖的问题,list而是一种检查类型的更Python方式。

Your issue is that you have re-defined list as a variable previously in your code. This means that when you do type(tmpDict[key])==list if will return False because they aren’t equal.

That being said, you should instead use isinstance(tmpDict[key], list) when testing the type of something, this won’t avoid the problem of overwriting list but is a more Pythonic way of checking the type.


回答 1

您应该尝试使用 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"

编辑1:之间的差异isinstance()type()为什么isinstance()要检查最偏爱的方式是,isinstance()除了检查的子类,而type()没有。

You should try using isinstance()

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

In your case

if isinstance(tmpDict[key], list):
      ## DO SOMETHING

To elaborate:

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"

The difference between isinstance() and type() though both seems to do the same job is that isinstance() checks for subclasses in addition, while type() doesn’t.


回答 2

这似乎为我工作:

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

This seems to work for me:

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