我想用一行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"]]如有任何帮助,我们将非常感谢:)
发布于 2020-03-25 13:11:44
只需使用嵌套的列表理解:
>>> [[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']]https://stackoverflow.com/questions/60843276
复制相似问题