检查python中的type == list

Ben*_*ist 124 python

我可能在这里有一个脑屁,但我真的无法弄清楚我的代码有什么问题:

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

输出是<type 'list'>但if语句永远不会触发.谁能在这里发现我的错误?

d-c*_*der 140

你应该尝试使用 isinstance()

if isinstance(object, list):
       ## DO what you want
Run Code Online (Sandbox Code Playgroud)

在你的情况下

if isinstance(tmpDict[key], list):
      ## DO SOMETHING
Run Code Online (Sandbox Code Playgroud)

编辑:在看到我的回答评论后,我想到详细阐述它.

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"
Run Code Online (Sandbox Code Playgroud)


Ffi*_*ydd 103

您的问题是您已list在代码中重新定义为变量.这意味着当你这样做type(tmpDict[key])==list时会False因为不相等而返回.

话虽这么说,你应该isinstance(tmpDict[key], list)在测试某种类型时使用,这不会避免覆盖的问题,list但是更像Pythonic的方式来检查类型.

  • 好的。“更Pythonic”是一个广泛的概念。只是为了教育:[*what-are-the-differences- Between-type-and-isinstance?*](/sf/ask/108486101/ Between-类型和实例) (2认同)

Pro*_*eus 20

这似乎对我有用:

>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True
Run Code Online (Sandbox Code Playgroud)


Ara*_*mar 11

Python 3.7.7

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


rem*_*icz 5

虽然不像isinstance(x, list)人们可以使用的那么简单:

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

我有点喜欢这种简单的聪明