简体   繁体   English

在python中检查type == list

[英]Checking if type == list in python

I 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.输出是<type 'list'>但 if 语句永远不会触发。 Can anyone spot my error here?谁能在这里发现我的错误?

You should try using isinstance()您应该尝试使用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. isinstance()type()之间的区别虽然两者似乎做同样的工作,但isinstance()会另外检查子类,而type()不会。

Your issue is that you have re-defined list as a variable previously in your code.您的问题是您之前在代码中将list重新定义为变量。 This means that when you do type(tmpDict[key])==list if will return False because they aren't equal.这意味着当您执行type(tmpDict[key])==list if 将返回False因为它们不相等。

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.话虽如此,您应该在测试某物的类型时改为使用isinstance(tmpDict[key], list) ,这不会避免覆盖list的问题,而是一种更 Pythonic 的检查类型的方法。

This seems to work for me:这似乎对我有用:

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

Python 3.7.7 Python 3.7.7

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

Although not as straightforward as isinstance(x, list) one could use as well:虽然不像isinstance(x, list)那样简单,但也可以使用:

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

and I kind of like the simple cleverness of that我有点喜欢那种简单的聪明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM