[clug] Two level python iterator
jm
jeffm at ghostgun.com
Wed Dec 8 21:07:36 MST 2010
Thanks. That was it. After posting the original message I keep playing
with the code, but couldn't work out why I was getting generator type
object is the print statement in main's for-loop. It turns out I had
almost exactly the same code as you do, but I'd put it in the next()
method instead of the __iter__() method as you do.
Thanks again,
Jeff.
On 9/12/10 2:22 PM, Jason wrote:
> I dont use these features much myself but I think this will do what
> you want
>
> from collections import defaultdict
>
> class TwoLevel(object):
>
> def __init__(self):
> self.data = defaultdict(dict)
>
> def add_data(self, idx1, idx2, value):
> self.data[idx1][idx2] = value
>
> def __iter__(self):
> for firstLevel in self.data.values():
> for secondLevel in firstLevel.values():
> yield secondLevel
> raise StopIteration()
>
> if __name__ == "__main__":
> store = TwoLevel()
> # with a bit of hand waving store a bunch of data
> for i in range(0, 10):
> for j in range(20,30):
> store.add_data(i,j, "%s: %s"%(i,j))
> # do something with entries
> for entry in store:
> print entry
>
> Jason
>
>
> On Thu, 09 Dec 2010 13:56:15 +1100, jm <jeffm at ghostgun.com> wrote:
>
More information about the linux
mailing list