查看python中是否存在列表或dict的最简单方法是什么?
我使用以下但这不起作用:
if len(list) == 0:
print "Im not here"
Run Code Online (Sandbox Code Playgroud)
谢谢,
您可以使用try/except块:
try:
#work with list
except NameError:
print "list isn't defined"
Run Code Online (Sandbox Code Playgroud)
当您尝试引用解释器引发的不存在的变量时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)