[clug] Two level python iterator
Hugh Fisher
hugh.fisher at anu.edu.au
Wed Dec 8 20:20:26 MST 2010
jm wrote:
> One for the python developers out there.
>
> I have a class which stores data in a hash of a hash and I which I wish
> to iterate over all the entries. Something like that shown below. What
> do I write for the __iter__ and next methods so that I can loop over the
> data with one for loop? Been thinking in languages other than python
> lately and just can't see the answer at the moment.
>
> class TwoLevel:
> ....
> def add_data(self, idx1, idx2, value):
> self.data[idx1][idx2] = value
>
> def __iter__(self):
> # what goes here
>
> def next(self):
> # and here
>
>
You could use the itertools module, which creates iterators over
multiple iterable objects. (I'm assuming you use lists or something
for the levels of your data structure.)
import itertools
def __iter__ (self):
return itertools.chain.from_iterable(self.data)
# No next(self) required
If you need to control the order a bit more precisely or munge your
own data structures, the code is something like:
def __iter__ (self):
return self # Object itself implements next()
def next (self):
for outer in self.data:
for inner in outer:
yield inner
raise StopIteration
Hope this helps.
cheers,
Hugh Fisher
More information about the linux
mailing list