【问题标题】:Python Find All Children And GrandchildrenPython 查找所有子孙
【发布时间】:2023-04-01 00:37:01
【问题描述】:

我有一个 SQL 查询,可以找到食谱所需的所有成分。

Parent Child Variation Level
Pizza Margherita pizza dough 1 -1
Pizza Margherita tomato sauce with pork 1 -1
Pizza Margherita pizza dough 2 -1
Pizza Margherita tomato sauce with beef 2 -1
pizza dough flour 1 -2
pizza dough water 1 -2
pizza dough flour 1 -2
pizza dough water 1 -2
tomato sauce with pork tomato sauce 1 -3
tomato sauce with pork pork 1 -3
tomato sauce with beef tomato sauce 1 -3
tomato sauce with beef beef 1 -3

一个玛格丽特披萨可能有多个食谱(或在我的情况下的变化),并且这些食谱可以共享相同的孩子。

我需要转换我的 SQL 结果:

_content = [
  ('Pizza Margherita', 'pizza dough', 1, -1),
  ('Pizza Margherita', 'tomato sauce with pork', 1, -1),
  ('Pizza Margherita', 'pizza dough', 2, -1),
  ('Pizza Margherita', 'tomato sauce with beef', 2, -1),
  (...so on and so forth)
]

到如下所示的 python 字典:

如果孩子的变异相同,他们将被放在字典下 {“伪”:真,“孩子”:[{“文本:{“名称”:“child_of_variation_1”},“孩子”:[]},{“文本:{“名称”:“another_child_of_variation_1”},“孩子": [其他孩子] }]

谁能建议一种更 Pythonic 的方式将元组列表转换为字典?

【问题讨论】:

  • “谁能建议一种更 Pythonic 的方式来解决这个问题?” 什么是“this”?您提交了数据,但您要解决的问题是什么?

标签: python json dictionary recursion hierarchical-data


【解决方案1】:

我表现不佳的尝试:

master = {"text": {"name": master_name, "data-level": 0}, "children": []}

def find_children(parent_dict):
    children_container = []

    for i, _row in enumerate(_content):
        parent, child, variation, level = _row
        item_dict = {"text": {"name": child, "data-level": level, "data-variation": variation},
                     "children": []
                     }

        if level + 1 == parent_dict["text"]["data-level"] \
                and str(parent).lower() == str(parent_dict["text"]["name"]).lower() \
                and _row not in children_container:

            item_dict["children"] = find_children(item_dict)
            if item_dict not in children_container:
                children_container.append(item_dict)

    # ! - group children by variation then put under same pseudo dict
    variations = set(map(lambda x: x["text"]["data-variation"], children_container))
    new_children_container = [
        {"pseudo": True,
         "children": [y for y in children_container if y["text"]["data-variation"] == x]} for x in variations
    ]
    return new_children_container

master["children"] = find_children(master)

仅在处理小列表时才成功。结果超过 1000 行时卡住。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    相关资源
    最近更新 更多