recursion - Walk recursively through childs of a list in Python -
i try recursively print sentences nested list of lists
i want obtain list containing
['big bad dog', 'big fluffy cat', 'small blue happy pony', 'small frog']
here code, don't work...
am on right path or should structure data in way achieve goal?
from pprint import pprint dirs = [ { 'kw': 'big', 'childs': [ { 'kw': 'bad', 'childs': [ { 'kw': 'dog' } ] }, { 'kw': 'fluffy', 'childs': [ { 'kw': 'cat' } ] } ] }, { 'kw': 'small', 'childs': [ { 'kw': 'blue', 'childs': [ { 'kw': 'happy', 'childs': [ { 'kw': 'pony' } ] } ] }, { 'kw': 'frog' } ] }, ] def traverse(d, l): kw = d.get('kw') c = d.get('childs') l.append(kw) if c: cc in c: l = traverse(cc, l) return l r = traverse(dirs[0], []) pprint(r)
as usual, generators work nicely recursive structures
def traverse(i): d in i: childs = d.get('childs') j in traverse(childs) if childs else ['']: yield d['kw']+' '+j res = list(traverse(dirs))
in python3.3, becomes
def traverse(i): d in i: c = d.get('childs') yield (d['kw']+' '+j j in (traverse(c) if c else ['']))
Comments
Post a Comment