简体   繁体   中英

How can i iterate through a python dict and reach easily the leaves?

I am trying to iterate a graph-dict object and reach every time the leave nodes, and i want to do it for different level of depth of the graph (if the leaves are in a deeper level )

{'Node': [0, 0, 0],
 'children': [{'Node': [1, 0, 0],
   'children': [{'Node': [2, 0, 0], 'children': []},
    {'Node': [1, 1, 0], 'children': []},
    {'Node': [1, 0, 1], 'children': []}]},
  {'Node': [0, 1, 0],
   'children': [{'Node': [1, 1, 0], 'children': []},
    {'Node': [0, 2, 0], 'children': []},
    {'Node': [0, 1, 1], 'children': []}]},
  {'Node': [0, 0, 1],
   'children': [{'Node': [1, 0, 1], 'children': []},
    {'Node': [0, 1, 1], 'children': []},
    {'Node': [0, 0, 2], 'children': []}]}]}

In particular i want to do something with this leaves nodes,(i have a function that can add other children) but with a parallel logic, using libraries like multiprocessing or joblib exc..

You can use recursion in this case. Below is a sample code.

graph={'Node': [0, 0, 0],
 'children': [{'Node': [1, 0, 0],
   'children': [{'Node': [2, 0, 0], 'children': []},
    {'Node': [1, 1, 0], 'children': []},
    {'Node': [1, 0, 1], 'children': []}]},
  {'Node': [0, 1, 0],
   'children': [{'Node': [1, 1, 0], 'children': []},
    {'Node': [0, 2, 0], 'children': []},
    {'Node': [0, 1, 1], 'children': []}]},
  {'Node': [0, 0, 1],
   'children': [{'Node': [1, 0, 1], 'children': []},
    {'Node': [0, 1, 1], 'children': []},
    {'Node': [0, 0, 2], 'children': []}]}]}

def collect_children(nodes):
  children=[]
  for node in nodes:
    if len(node['children'])!=0:
      children+=node['children']
  return children

def get_leaves(nodes, depth):
  if depth==0:
    return []
  elif depth==1:
    return collect_children(nodes)
  else:
    return get_leaves(collect_children(nodes),depth-1)

print(get_leaves([graph],2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM