Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find all the possible combinations of a list of lists (in Python)?

Tags:

python

I have the following structure in Python:

letters = [['a', 'b', 'c'], ['p', 'q', 'r', 's'], ['j', 'k', 'l']]

I would like to find all the possible combinations of letters in the order that they currently exist. For the example above this would be:

apj
apk
apl
aqj
aqk
aql
...
csk
csl

This seems like it should be a very simple thing to do but I cannot figure it out.

like image 397
Peter Horne Avatar asked Jun 07 '10 13:06

Peter Horne


1 Answers

In Python 2.6 or newer you can use itertools.product:

>>> import itertools
>>> map(''.join, itertools.product(*letters))
apj
apk
apl
aqj
aqk
aql
...etc...
csk
csl
like image 97
Mark Byers Avatar answered Sep 21 '22 03:09

Mark Byers