python - 在 Python 中递归遍历字典?

标签 python recursion dictionary lambda list-comprehension

递归遍历字典的更好方法是什么? 我可以使用 lambda 或/和列表推导来完成吗?

我有:

[
  {
    "id": 1,
    "children": [
      {
        "id": 2,
        "children": []
      }
    ]
  },
  {
    "id": 3,
    "children": []
  },
  {
    "id": 4,
    "children": [
      {
        "id": 5,
        "children": [
          {
            "id": 6,
            "children": [
              {
                "id": 7,
                "children": []
              }
            ]
          }
        ]
      }
    ]
  }
]

我要:

[1,2,3,4,5,6,7]

最佳答案

你可以递归地遍历你的字典,使用这个通用的生成器函数,就像这样

def rec(current_object):
    if isinstance(current_object, dict):
        yield current_object["id"]
        for item in rec(current_object["children"]):
            yield item
    elif isinstance(current_object, list):
        for items in current_object:
            for item in rec(items):
                yield item

print list(rec(data))
# [1, 2, 3, 4, 5, 6, 7]

关于python - 在 Python 中递归遍历字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22951855/

相关文章:

.net 3.5 中深度/递归对象比较的 C# 实现

python - 将递归问题代码从 Python 转换为 Common Lisp

python - 对数据帧字典中的每个数据帧进行排序

python - 如果不手动寻找 eof,则在以追加模式打开的 Python 文件对象上调用 tell() 返回 0

python - 从列表中查找唯一索引

python - 将文件从未知文件夹移动到其他文件夹

python - 如何在 sqlacodegen 模型中使用 .query 属性

node.js - 有没有更好的方法在 typescript 中编写这个递归方法

swift - Swift Dictionary 中连续语句必须用 ";"分隔

arrays - 快速将数组序列化为对象