简体   繁体   English

将对象列表转换为单个列表的列表

[英]convert a list of objects to a list of single lists

I have a question: I have a list of nested objects that I managed to change it to this format:我有一个问题:我有一个嵌套对象列表,我设法将其更改为这种格式:

converted_nested_list = [
    {"cmd_count": 2, "name": "jacky", "powered": 10},
    {"cmd_count": 9, "name": "madi", "powered": 26},
    {"cmd_count": 7, "name": "alisson", "powered": 77},
]

if you can just explain to me how can I converted to this format in a pythonic way:如果您可以向我解释如何以pythonic方式转换为这种格式:

wanted_format = {
    "person_names": ["jacky","madi","alisson"],
    "person_details":[
        {"label":"cmd_count", "stats":[2,9,7]},
        {"label":"powered","stats":[10,26,77]}
    ]
}

I would use a defaultdict to group the labels and values, and then use that dict to create your final structure.我会使用defaultdict对标签和值进行分组,然后使用该 dict 来创建最终结构。

from collections import defaultdict

converted_nested_list = [
    {"cmd_count": 2, "name": "jacky", "powered": 10},
    {"cmd_count": 9, "name": "madi", "powered": 26},
    {"cmd_count": 7, "name": "alisson", "powered": 77},
]

label_stats = defaultdict(list)
for value in converted_nested_list:
    for label, stat in value.items():
        label_stats[label].append(stat)

result = {
    "person_names": label_stats["name"],
    "person_details":[ 
        {"label": label, "stats": stats}
        for label, stats in label_stats.items()
        if label != "name"
    ] 
}

Using list comprehension:使用列表理解:

wanted_format = {
    'person_names': [person['name'] for person in converted_nested_list],
    'person_details': [
        {'label': 'cmd_count', 'stats': [person['cmd_count'] for person in converted_nested_list]},
        {'label': 'powered', 'stats': [person['powered'] for person in converted_nested_list]}
    ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM