On 10/21/2012 7:29 PM, David wrote:
I have a tree-like data structure, the basic elements are hash tables,
and they are grouped into lists, like [[{'a':1},[{'b':2}]]].
And I want to flat the lists and visit hash table one by one, like {'a':1}, 
{'b':2}.
But my program didn't work as I wish. When it entered the 2nd
flat_yield, it threw a GeneratorExit. Is there anything wrong?

1. The Python version is not specified.
2. You used 2.x; in 3.3 the code does exactly what I would expect, which is to say, nothing. No output, no error, no traceback ;-)
3. The traceback is missing from this post.

#- - - - - - - - - -
def flat_yield(tbl_list):
     for t in tbl_list:
         if type(t) == type({}):
             yield t
         elif type(t) == type([]):
             flat_yield(t)

4. Think harder about what that expression does.

a = [[{'a':1},[{'b':2}]]]
for i in flat_yield(a):
     print i

Hint: it calls flat_yield, which returns a generator, which is then discarded. You might have well written 'pass'.

Solution: use the recursively called generator and recursively yield what it yields. Replace 'flat_yield(t)' with

            for item in flat_yield(t):
                yield item

and the output is what you want.

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to