'Python: Build edges based on nested list
I need an example to build edges based on nested list in python.
Current code:
data = [257, [269, [325]],[4,''],[0,'']]
def iter(o, tree_types=(list, tuple)):
if isinstance(o, tree_types):
for value in o:
if isinstance(value, list):
for subvalue in iter(value, list):
yield subvalue
else:
yield value
else:
yield o
final_list = list(iter(data))
print('\nfinal_list = {0}'.format(final_list))
edges = []
l = final_list
for first, second in zip(l, l[1:]):
edges.append((first, second))
print('\nedges:{0}'.format(edges))
Current Output: final_list = [257, 269, 325, 4, '', 0, ''] edges = [(257, 269), (269, 325), (325, 4), (4, ''), ('', 0), (0, '')]
Desired output:
edges = [(257, 269), (269, 325), (257, 4), (4, ''), (257,0), (0, '')]
Solution 1:[1]
Part of the problem is you have flattened the list (of lists) and therefore no longer know which nodes where joined to which. The use of zip
assumes these have been lined up in pairs somehow.
If your iterator yields a source and destination or sink node in a pair, you can preserve this.
You aren't using the tree_types
, so without that, this works for your input:
def iter(o):
source = o[0]
for subgraph in o[1:]:
if isinstance(subgraph, list):
yield from iter(subgraph)
sink = subgraph[0]
if isinstance(sink, list):
yield (source, sink[0])
else:
yield (source, sink)
else:
yield (source, subgraph)
This has a few assumptions... for example, that the data isn't empty and the first item is a single node.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | doctorlove |