Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all combination from multiple lists?

Tags:

python

I am not sure that my question is correct but I don't know how to explain it otherwords. So I've got some lists like

a = ['11', '12']
b = ['21', '22']
c = ['31', '32']

And i need to get something like:

result = [
    ['11', '21', '31'],
    ['11', '21', '32'],
    ['11', '22', '31'],
    ['11', '22', '32'],
    ['12', '21', '31'],
    ['12', '21', '32'],
    ['12', '22', '31'],
    ['12', '22', '32']
]
like image 888
GhostKU Avatar asked May 25 '17 08:05

GhostKU


People also ask

How do you generate all possible combinations of multiple lists?

Add a Custom Column to and name it List1. Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!


2 Answers

User itertools, combinations:

import itertools
a = ['11', '12']
b = ['21', '22']
c = ['31', '32']
list(itertools.combinations(itertools.chain(a,b,c), 3))
[('11', '12', '21'), ('11', '12', '22'), ('11', '12', '31'), ('11', '12', '32'), ('11', '21', '22'), ('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('11', '31', '32'), ('12', '21', '22'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32'), ('12', '31', '32'), ('21', '22', '31'), ('21', '22', '32'), ('21', '31', '32'), ('22', '31', '32')]

or product:

list(itertools.product(a,b,c))
[('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32')]
like image 69
Netwave Avatar answered Oct 13 '22 16:10

Netwave


You need itertools.product which returns cartesian product of input iterables.

>>> a = ['11', '12']
>>> b = ['21', '22']
>>> c = ['31', '32']
>>>
>>> from itertools import product
>>>
>>> list(product(a,b,c))
[('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32')]

And you can use a list comprehension to convert tuples to lists:

>>> [list(i) for i in product(a,b,c)]
[['11', '21', '31'], ['11', '21', '32'], ['11', '22', '31'], ['11', '22', '32'], ['12', '21', '31'], ['12', '21', '32'], ['12', '22', '31'], ['12', '22', '32']]
like image 23
McGrady Avatar answered Oct 13 '22 16:10

McGrady