x = {
"a":1,
"b":[
{
"a":2,
"b":[ { "a":3, }, { "a":4, } ]
}
]
}
input_stack = [x]
output_stack = []
while input_stack:
# for the first element in the input stack
front = input_stack.pop(0)
b = front.get('b')
# put all nested elements onto the input stack:
if b:
input_stack.extend(b)
# then put the element onto the output stack:
output_stack.append(front)
output_stack ==
[{'a': 1, 'b': [{'a': 2, 'b': [{'a': 3}, {'a': 4}]}]},
{'a': 2, 'b': [{'a': 3}, {'a': 4}]},
{'a': 3},
{'a': 4}]
不确定Python实现,但在JavaScript中,这可以使用递归实现:
只有当对象键名是而不是数字时,这才会按预期工作。你知道吗
见JSFiddle。你知道吗
我会使用一个输入和输出堆栈:
output_stack
可以是dict
的原因。然后更换与
相关问题 更多 >
编程相关推荐