为什么下面的代码不能在列表理解中使用IF条件? “响应”中不存在“内容”,因此应返回空列表。

response={"Contents1" : [ {"a" : 1, "b" : 1},{"a" : 2, "b" : 2},{"a" : 3, "b" : 3 } ] }
lst=[item["a"] for item in response["Contents"] if "Contents" in response]
print(lst)


KeyError:“内容”

下面的工作正常,并且不打印任何输出,因为“响应”中不存在“目录”

if "Contents" in response:
    for item in response["Contents"]:
    print(item["a"])

最佳答案

理解仍在尝试使用不存在的密钥访问字典。您可以改为执行以下操作:

[item["a"] for k in response for item in response[k] if k == "Contents"]

关于python - 带有IF子句的列表理解,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37793826/

10-12 17:24
查看更多