In Python, is there a compressed way to use list comprehension with multiple iterators?

Basically, I would like to build an understanding of the list over the "Cartesian product" of two iterators. Think of the following Haskell code :

[(i,j) | i <- [1,2], j <- [1..4]] 

what gives

 [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] 

Is it possible to get similar behavior in Python in short form?

+7
python iterator list-comprehension
source share
4 answers

Are you asking about this?

 [ (i,j) for i in range(1,3) for j in range(1,5) ] 
+14
source share

The Cartesian product is located in the itertools module (in version 2.6).

 >>> import itertools >>> list(itertools.product(range(1, 3), range(1, 5))) [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)] 
+7
source share

A funny fact about nested understanding: it simulates nested loops for, so internal ones can use values ​​from external ones. It is not useful in Cartesian packaging, but it is useful to know. For example:

 [ (i,j) for i in range(10) for j in range(i) ] 

generates all pairs (i,j) , where 0>=i>j>10 .

+4
source share

This is similar to what you describe:

[[a, b] for a in the range (1.3) for b in the range (1.5)]

UPDATE: Drat! You must reload the page to see S.Lott's answer before posting. Hmm ... what to do for a small added value? Perhaps a short testament to the usefulness of interactive mode with Python.

I came recently from the background with Perl, so with such problems it’s very useful for me to type β€œpython” on the command line and switch to interactive mode, but simply: a) start trying, and b) improve the subtleties by pressing the up arrow and adjusting my previous attempt until I get what I want. Every time I fog for a keyword, help is at hand. Just type: help ("some_keyword"), read the brief summary, then press "Q" and I will return to the line in a direct conversation with the python interpreter.

Recommended if you are a beginner and do not use it.

+2
source share

All Articles