在python中检查type == list

新手上路,请多包涵

我无法弄清楚我的代码有什么问题:

 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 语句永远不会触发。谁能在这里发现我的错误?

原文由 Benjamin Lindqvist 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 631
2 个回答

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

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

原文由 Ffisegydd 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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。

原文由 d-coder 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏