Python : generate all combination from values in d

2019-01-25 10:35发布

问题:

I would like to generate all combinations of values which are in lists indexed in a dict, like so :

{'A':['D','E'],'B':['F','G','H'],'C':['I','J']}

Each time, one item of each dict entry would be picked and combined to items from other keys, so we can have :

['D','F','I']
['D','F','J']
['D','G','I']
['D','G','J']
['D','H','I']
...
['E','H','J']

I know there is a something to generate combinations of items in list in itertools but I don't think I can use it here since I have different "pools" of values.

Is there any existing solution to do this, or how should I proceed to do it myself, I am quite stuck with this nested structure.

回答1:

import itertools as it

my_dict={'A':['D','E'],'B':['F','G','H'],'C':['I','J']}
allNames = sorted(my_dict)
combinations = it.product(*(my_dict[Name] for Name in allNames))
print(list(combinations))

which prints

[('D', 'F', 'I'), ('D', 'F', 'J'), ('D', 'G', 'I'), ('D', 'G', 'J'), ('D', 'H', 'I'), ('D', 'H', 'J'), ('E', 'F', 'I'), ('E', 'F', 'J'), ('E', 'G', 'I'), ('E', 'G', 'J'), ('E', 'H', 'I'), ('E', 'H', 'J')]



回答2:

as a complement, here is a 3-liner that does it in pure python so that you get the idea, but itertools is indeed more efficient.

res = [[]]
for _, vals in my_dict.items():
    res = [x+[y] for x in res for y in vals]
print(res)


回答3:

from itertools import combinations

a=['I1','I2','I3','I4','I5']

list(combinations(a,2))

and the output will be

[('I1', 'I2'), ('I1', 'I3'), ('I1', 'I4'), ('I1', 'I5'), ('I2', 'I3'), ('I2', 'I4'), ('I2', 'I5'), ('I3', 'I4'), ('I3', 'I5'), ('I4', 'I5')]



回答4:

Beside using Cartesian products provide by Maryam, you could also use the naive nested loop to get what you want.