开发者

Python iterations

Has anybody any idea why this code fails to run smooth? It seems not to like iterations with the yield keyword: I am trying to mine all the numbers from any level of lists or dicts ( especially interested in lists ). At the second iteration it finds [2,开发者_C百科3] but fails to print 2 and 3 one after other...Imagine also that I could have many levels of lists.

def digIn( x ):
    try:
        if isDict(x) or isList(x):
            print "X:", x
            for each in x:
                print "each:", each
                if isDict(each) or isList(each):
                    digIn(each)
                else:
                    yield each
        else:
            yield x
    except Exception,ex:
        print ex

print "STARTING OVER"
for i in digIn( [1,[2,3]] ):
    print i


You should 're-yield' the generator to iterate through all list elements recursively.

if isDict(each) or isList(each):
     for elem in digIn(each):
         yield elem
else:
     yield each


digIn(each) is incorrect. You must iterate over it, and yield each value in turn.


When you recursively call digIn the inner yields don't cause values to be yielded from the outer call. Instead the recursive digIn is returning a generator and then you are silently discarding that generator and losing the inner items.

You need to explicitly yield the results from the recursive call.

if isDict(each) or isList(each):
    for innerItem in digIn(each):
        yield innerItem
else:
    yield each
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜