首页 > 解决方案 > 在单行中将 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"]]

任何帮助表示赞赏:)

标签: python-3.xlist-comprehensionnested-loops

解决方案


只需使用嵌套列表推导:

>>> [[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']]

推荐阅读