[Python-Dev] Product iteration

Moshe Zadka Moshe Zadka <moshez@math.huji.ac.il>
Tue, 25 Jul 2000 18:51:54 +0300 (IDT)


A large part of the problem in list comprehensions (I think) is that we
need to allow more then one "for" term, so we can iterate over the product
of several lists. Why not solve that the same way we solved the parallel
iteration problem, by using a function, called, say, "product".

Then list comprehensions can limited to be (in pseudo formal grammar):

'[' expr 'for' var 'in' seq [ 'if' pred ] ']'

Such that "var" can be anything that can today be in a for loop, e.g.,

(x, (y, z))

Then we wouldn't have the irksome problem of how for's and if's intermix:
the predicate at the end can be an and'ed sequence of predicates.


Reference implemntation:
class _Producter:

        def __init__(self, lists):
                if not lists:
                        raise TypeError("must receive at least one list")
                self.lists = lists
                self.lengths = map(len, lists)
                self.n_lists = len(lists)

        def __getitem__(self, i):
                if i<0:
                        raise ValueError("only non-negative indices supported")
                ret = [None] * self.n_lists
                for j in range(self.n_lists):
                        i, i_j = divmod(i, self.lengths[j])
                        ret[j] = self.lists[j][i_j]
                if i != 0:
                        raise IndexError("not that many items")
                return tuple(ret)

def product(*lists):
        return _Producter(lists)


--
Moshe Zadka <moshez@math.huji.ac.il>
There is no IGLU cabal.
http://advogato.org/person/moshez