python-3.x - 在单行中将 JSON 嵌套数组转换为 Python 嵌套列表
问题描述
我想使用单行 Python 方法将 JSON 嵌套数组转换为 Python 嵌套列表。
下面是我的 JSON 嵌套数组的示例:
my_dict = {
"background": "This is a test text.",
"person": [
{"name": "Max", "tranx_info": [
{"tranx_date":"7/1/2020","amount": 82 },
{"tranx_date":"27/2/2017","amount":177 }]
},
{"name": "Lily", "tranx_info": [
{"tranx_date":"12/7/1989","amount": 165 },
{"tranx_date":"28/2/1998","amount": 200 },
{"tranx_date":"28/2/2098","amount": 34 }]
}
]
}
我假设这将是 Python 中的嵌套列表理解?到目前为止我已经尝试过,但我只能将结果放入列表中:
tranx_date_result = [x["tranx_date"] for y in my_dict["person"] for x in y["tranx_info"]]
#output
>>> ["7/1/2020","27/2/2017","12/7/1989","28/2/1998","28/2/2098"]
我希望我的"tranx_date"
结果在一个嵌套列表中;像这样的东西:
tranx_date_result = [["7/1/2020","27/2/2017"],["12/7/1989","28/2/1998","28/2/2098"]]
任何帮助表示赞赏:)
解决方案
只需使用嵌套列表推导:
>>> [[x["tranx_date"] for x in y["tranx_info"]] for y in my_dict["person"]]
[['7/1/2020', '27/2/2017'], ['12/7/1989', '28/2/1998', '28/2/2098']]
推荐阅读
- javascript - 在节点中执行 pycodestyle 没有错误没有输出
- amazon - 哪个是亚马逊 MWS 的测试类别
- python - 过滤和替换 Pandas 中的子字符串
- linux - 如何在 Linux Shell 脚本中替换从另一个文件中获取输入的字符串
- java - 如何通过 URI 复制文件
- java - Springboot 调用 ESAPI 显示异常
- jquery - Rails 5:如何运行 edit.js.erb 文件
- java - 使用@AllowFeature 控制器方法播放Framework 1.x 功能测试
- c# - c#设置gcServer启用后不创建转储文件
- typescript - 打字稿 find() 并返回索引