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

时间:2009-10-12 01:28:34

标签: 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

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

3 个答案:

答案 0 :(得分: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:

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

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

for b in maybe_list(lambda: a["key"][0][0]):

答案 1 :(得分:3)

我会写一个像这样的自定义索引器函数:

def safe_indexer(obj, *indices):
    for idx in indices:
        if not obj: break

        if hasattr(obj, "get"):
            obj = obj.get(idx)
        else:
            obj = obj[idx]

    return obj

用法:

a = {"key": {0: {0: "foo"} } };
print safe_indexer(a, "key", 0, 0)
print safe_indexer(a, "bad", 0, 0)

输出:

foo
None

答案 2 :(得分:2)

这个怎么样:

try:
    for b in a['key'][0][0]:
        # do stuff.
except KeyError, TypeError, IndexError:
    # respond appropriately.