python - recursively exploding a list of list to "atomic list" -



python - recursively exploding a list of list to "atomic list" -

i having difficulties nested lists of lists in python (this construction of geojson coordinates )

here illustration

updated illustration avoid confusion

dictofcoordinates = { 'a': [1,1], 'b': [[2, 2], [2,2], [2, 2]], 'c': [[[3,3], [3, 3], [3, 3]]], 'd': [[[41, 41], [41, 41]], [[42, 42], [42, 42]]] }

what want lists not contains anyhing else pairs (of coordinates). phone call "atomic list of list" (for lack of improve term)

so

- : list [1, 1] - b : [[2, 2], [2,2], [2, 2]] - c : [[3,3], [3, 3], [3, 3]] - d : 2 lists [[41, 41], [41, 41]] , [[42, 42], [42, 42]]]

taking inspriation here tried

def explodetolist(xlist): x1 in xlist: if isinstance(x1[0], (float, int, long)): yield x1 else: x2 in explodetolist(x1): yield x2

but not work

for x in explodetolist(dictofcoordinates.values()): print x

any help appreciated.

you need check if element[0] list.

def flatten(items): elem in items: if isinstance(elem[0],list): sub_elem in elem: yield sub_elem else: yield elem print list(flatten(dictofcoordinates.values())) [[1, 1], [[3, 3], [3, 3], [3, 3]], [2, 2], [2, 2], [2, 2], [[41, 41], [41, 41]], [[42, 42], [42, 42]]]

to match new output:

def flatten(items): elem in items: if sum(isinstance(i, list) in elem) == 0 or sum(isinstance(i, list) in elem[0]) == 0: yield elem else: sub_elem in elem: yield sub_elem print (list(flatten(dictofcoordinates.values()))) [[1, 1], [[3, 3], [3, 3], [3, 3]], [[2, 2], [2, 2], [2, 2]], [[41, 41], [41, 41]], [[42, 42], [42, 42]]]

python json list geojson

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -