检查类型==列表在python中


185

我可能在这里放屁,但是我真的无法弄清楚我的代码出了什么问题:

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语句从不触发。有人可以在这里发现我的错误吗?


3
您曾经list在某个地方用作变量吗?请注意,如果您正在使用REPL或类似版本,则可能仍会在不久前对其进行重新定义。
Ffisegydd 2014年

..... Woooowww ...绝对是一门关于软类型语言缺点的课程。哇...
Benjamin Lindqvist 2014年

将其添加为答案,我会接受。谢谢。
Benjamin Lindqvist 2014年

1
Pylint和朋友将来会为您提供帮助(实际上,我不会将此称为缺点)。

Answers:


139

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

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


真好 “更多Pythonic”是一个广泛的概念。只是为了教育:类型和实例之间的区别是什么?
哈维

221

您应该尝试使用 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()没有。


22

这似乎为我工作:

>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.