在python中检查type==list

2024-04-24 14:36:15 发布

您现在位置: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语句从不触发。有人能指出我的错误吗?


Tags: key代码inforiftimeistype
3条回答

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

也就是说,您应该在测试某个类型时使用^{},这并不能避免覆盖list的问题,而是检查该类型的一种更为python的方法。

这似乎对我有用:

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

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

相关问题 更多 >