用IF claus列出理解

2024-09-30 08:36:07 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么下面的代码不能处理列表理解中的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"])

Tags: 代码in内容列表forifresponsecontents
1条回答
网友
1楼 · 发布于 2024-09-30 08:36:07

“理解”仍在尝试使用一个不存在的键访问词典。您可以执行以下操作:

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

相关问题 更多 >

    热门问题