简体   繁体   中英

How to return the value of a recursive function

I have recursive function which walk nested dict and return needed key's value:

def recurs(l):
    for key in l.keys():
        if key == '_events':
            return l[key]
        else:
            recurs(l[key])

c=recurs(d)
print c

And how i can get these values?

The easiest way to get a flattened iterator is to write a generator function:

def recurs(l):
    for key in l.keys():
        if key == '_events':
            yield l[key]
        else:
            for x in recurs(l[key]):
                yield x

Just return it:

def recurs(l):
    for key in l.keys():
        if key == '_events':
            return l[key]
        else:
            return recurs(l[key])

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