【问题标题】:Checking if type == list in python在python中检查type == list
【发布时间】:2014-12-20 01:34:32
【问题描述】:

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

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

【问题讨论】:

  • 您是否曾在某处使用过list 作为变量?请注意,如果您正在使用 REPL 或类似的方式工作,它可能仍会在不久前重新定义。
  • .....Woooowww...绝对是关于软类型语言缺点的教训。哇...
  • 将其添加为答案,我会接受。谢谢。
  • Pylint 和朋友将来会帮助你(我不会说这是一个缺点,真的)。

标签: python


【解决方案1】:

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

isinstance()type() 之间的区别虽然两者似乎做同样的工作,但 isinstance() 会额外检查子类,而 type() 不会。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    【解决方案3】:

    这似乎对我有用:

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

    【讨论】:

      【解决方案4】:

      Python 3.7.7

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

      【讨论】:

        【解决方案5】:

        虽然不像isinstance(x, list) 那样简单,但也可以使用:

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

        我有点喜欢它的简单聪明

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-02-11
          • 2022-12-05
          • 2020-05-11
          • 2017-11-05
          • 2022-12-01
          • 2020-07-05
          • 1970-01-01
          相关资源
          最近更新 更多