[Python-Dev] For/while/if statements/comprehension/generator expressions unification
Jack Diederich
jack at performancedrivers.com
Tue Sep 20 19:56:45 CEST 2005
On Tue, Sep 20, 2005 at 10:20:44AM -0700, Josiah Carlson wrote:
> Try using the code I offered. It allows the cross of an aribitrary
> number of restartable iterables, in the same order as an equivalent list
> comprehension or generator expression.
>
> >>> list(cross([1,2], [3,4], [5,6]))
> [(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4,
> 5), (2, 4, 6)]
>
> There were a few hoops I had to jump through in cross in order to be
> able to hande single iterables as well as tuples embedded in the passed
> iterables, but they work as they should.
>
> >>> list(cross([(1,1),(2,2)], [(3,3),(4,4)], [(5,5),(6,6)]))
> [((1, 1), (3, 3), (5, 5)), ((1, 1), (3, 3), (6, 6)), ((1, 1), (4, 4), (5,
> 5)), ((1, 1), (4, 4), (6, 6)), ((2, 2), (3, 3), (5, 5)), ((2, 2), (3, 3),
> (6, 6)), ((2, 2), (4, 4), (5, 5)), ((2, 2), (4, 4), (6, 6))]
This comes up on c.l.p every month or two. Folks offer their own solutions
optimized for speed, memory, or golfed for char length. I'll throw in my
same two bits as always,
sprat:~# python
Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import probstat
>>> c = probstat.Cartesian([[1,2], [3,4], [5,6]])
>>> list(c)
[[1, 3, 5], [2, 3, 5], [1, 4, 5], [2, 4, 5], [1, 3, 6], [2, 3, 6], [1, 4, 6], [2, 4, 6]]
>>> c = probstat.Cartesian([[(1,1),(2,2)], [(3,3),(4,4)], [(5,5),(6,6)]])
>>> list(c)
[[(1, 1), (3, 3), (5, 5)], [(2, 2), (3, 3), (5, 5)], [(1, 1), (4, 4), (5, 5)], [(2, 2), (4, 4), (5, 5)], [(1, 1), (3, 3), (6, 6)], [(2, 2), (3, 3), (6, 6)], [(1, 1), (4, 4), (6, 6)], [(2, 2), (4, 4), (6, 6)]]
The signature is slightly different (list of lists) but otherwise does
what you want. Unchanged since 2002!
http://probstat.sourceforge.net/
-jackdied
More information about the Python-Dev
mailing list