有没有更简洁的方法来链接Python中的空列表检查?

Dav*_*vy8 3 python coding-style

我有一个相当复杂的对象(反序列化的json,所以我没有太多的控制权)我需要检查是否存在并迭代一个相当深的元素,所以现在我有这样的东西:

if a.get("key") and a["key"][0] and a["key"][0][0] :
    for b in a["key"][0][0] :
        #Do something
Run Code Online (Sandbox Code Playgroud)

哪个有效,但很难看.似乎必须有更好的方法来做到这一点,那么什么是更优雅的解决方案?

Joh*_*kin 14

try:
  bs = a["key"][0][0]
# Note: the syntax for catching exceptions is different in old versions
# of Python. Use whichever one of these lines is appropriate to your version.
except KeyError, IndexError, TypeError:   # Python 3
except (KeyError, IndexError, TypeError): # Python 2
  bs = []
for b in bs:
Run Code Online (Sandbox Code Playgroud)

如果你不介意更长的行,你可以把它打包成一个函数:

def maybe_list(f):
  try:
    return f()
  except KeyError, IndexError, TypeError:
    return []

for b in maybe_list(lambda: a["key"][0][0]):
Run Code Online (Sandbox Code Playgroud)

  • 好的电话,忘了Python的哲学,最好是请求宽恕而不是许可.来自.NET,你试图避免尽可能多地抛出异常,这需要一些时间来习惯. (2认同)