gpt4 book ai didi

python - 带有 IF 子句的列表推导式

转载 作者:太空宇宙 更新时间:2023-11-03 16:28:38 25 4
gpt4 key购买 nike

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

key 错误:“内容”

下面工作正常,不会打印任何输出,因为“响应”中不存在“内容”

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com