为什么下面的代码不能处理列表理解中的IF条件?”“response”中不存在“Contents”,它应该返回空列表。你知道吗
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:'内容'
由于“response”中不存在“Contents”,因此下面的工作正常,不打印任何输出
if "Contents" in response:
for item in response["Contents"]:
print(item["a"])
“理解”仍在尝试使用一个不存在的键访问词典。您可以执行以下操作:
相关问题 更多 >
编程相关推荐