如何检查Python中是否存在列表

Ric*_*ckD 5 python

查看python中是否存在列表或dict的最简单方法是什么?

我使用以下但这不起作用:

if len(list) == 0:
    print "Im not here"
Run Code Online (Sandbox Code Playgroud)

谢谢,

Nic*_*las 9

您可以使用try/except块:

try:
    #work with list
except NameError:
    print "list isn't defined"
Run Code Online (Sandbox Code Playgroud)

  • 注意//是整数除法。使用#进行评论 (2认同)

daw*_*awe 6

当您尝试引用解释器引发的不存在的变量时NameError.但是,依赖代码中存在变量并不安全(最​​好将其初始化为None或其他东西).有时候我用过这个:

try:
    mylist
    print "I'm here"
except NameError:
    print "I'm not here"
Run Code Online (Sandbox Code Playgroud)


小智 5

对于列表:

if a_list:
    print "I'm not here"
Run Code Online (Sandbox Code Playgroud)

字典也是如此:

if a_dict:
    print "I'm not here"
Run Code Online (Sandbox Code Playgroud)

  • list和dict是内置类型。该代码将始终成功,即if语句中的条件。 (3认同)
  • 什么?你的意思是`如果不是a_list:打印“我不在这里”`?? (3认同)