递归遍历字典的更好方法是什么? 我可以使用 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/