Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get all possible combination of items from 2-dimensional list in python?

I didn't find a better way to phrase this question in the title. If you can, please edit.

I have a list of lists like this:

a = [['a','b'],[1,2]]

now, I'd like a function that spits out all possible combination like this:

[['a',1],['a',2],['b',1],['b',2]]

where nor the number of lists in a is known in advance, nor is the length of each of the sub lists known in advance, but all the combinations that come out should contain 1 item from every sublist.

like image 315
bigblind Avatar asked Nov 23 '11 22:11

bigblind


1 Answers

You need itertools.product():

>>> list(itertools.product(*a))
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]
like image 107
Sven Marnach Avatar answered Nov 17 '22 10:11

Sven Marnach