【问题标题】:Find parent sibling in mixed dict/list在混合字典/列表中查找父兄弟
【发布时间】:2017-09-20 01:03:24
【问题描述】:

我想在这个数组中找到父兄弟。

arr = {
    'children': [
        {
            'id':'item_1',
            'title':'Item 1',
            'children': [
                {
                    'id':'item_a',
                    'title':'Item A'
                },
                {
                    'id':'item_b',
                    'title':'Item B'
                },
                {
                    'id':'item_c',
                    'title':'Item C',
                    'children': [
                        {
                            'id':'item_i',
                            'title':'Item I'
                        },
                        {
                            'id':'item_ii',
                            'title':'Item II'
                        }
                    ]
                }
            ]
        }
    ]
}

例如,如果我将“item_b”放入方法中,它必须返回“item_1”(忽略“children”作为父级)。类似的东西:

>>> parent = get_parent(arr, 'item_i', ['children'])
>>> parent['id']
item_c
>>> parent = get_parent(arr, 'item_1', ['children'])
>>> parent['id']
None

我的身份证是独一无二的,所以我知道只有一个父母。

我查看了 mgilson 和 Claudiu 的示例,但我不知道如何将这些更改为我所追求的。 Claudius 解决方案看起来是正确的方向,但我的数组只返回 []。


编辑: ewcz 解决方案效果很好。我对其进行了一些修改以允许获取标题:

def get_parent(arr, item_id):
    L = [(None, arr)]
    while L:
        parent_item, item = L.pop()
        curr_id = item.get('id', None)
        if curr_id == item_id:
            return parent_item

        children = item.get('children', [])
        for child in children:
            L.append((item, child))

parent = get_parent(arr, 'item_i')
print(parent.get('id'))
print(parent.get('title'))

【问题讨论】:

  • 您确定标题中的“兄弟”一词吗?从描述看来,您只需要父项。兄弟项目是共享父项目的项目,例如您的示例中的 item_i 和 item_ii。
  • @gereleth 你可能是对的,但我在想id 和title 是children 的兄弟姐妹。
  • 我最近了解了 a* 算法,现在我看到@ewcz 代码与该算法非常相似。只是认为这可能会帮助任何谷歌员工:)

标签: python linux dictionary nested


【解决方案1】:

一种选择是遍历您的数组并在遍历到感兴趣的项目后立即返回父 ID:

def get_parent(arr, item_id):
    L = [(None, arr)]
    while L:
        parent_id, item = L.pop()

        curr_id = item.get('id', None)
        if curr_id == item_id:
            return parent_id

        children = item.get('children', [])
        for child in children:
            L.append((curr_id, child))

parent = get_parent(arr, 'item_i')

【讨论】:

  • 谢谢!在我的帖子中查看修改后的解决方案。
  • @NinjaFart 很高兴,虽然我认为修改会直接给你指定id的元素,而不是它的父元素...
  • Ups,你是对的。我已经更新了我的帖子 - 现在应该可以使用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-05
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多