Ken Nguyen Ken Nguyen - 2 months ago 9
Python Question

Python create list combination

I have a dictionary contain element and sequence count of element. I want to create a list of list that combined from these elements

Example

Input: dictElement = {"PA":2,"PB":2}

Expected Output:
[('PB0', 'PA0'),
('PB0', 'PA1'),
('PB1', 'PA0'),
('PB1', 'PA1')]





Input: dictElement = {"PA":2,"PB":2,"PC":3}

Expected Output:
[('PC0', 'PB0', 'PA0'),
('PC0', 'PB0', 'PA1'),
('PC0', 'PB1', 'PA0'),
('PC0', 'PB1', 'PA1'),
('PC1', 'PB0', 'PA0'),
('PC1', 'PB0', 'PA1'),
('PC1', 'PB1', 'PA0'),
('PC1', 'PB1', 'PA1'),
('PC2', 'PB0', 'PA0'),
('PC2', 'PB0', 'PA1'),
('PC2', 'PB1', 'PA0'),
('PC2', 'PB1', 'PA1')]


Note: Number elements of dictionary can be change

Answer

You haven't specified in what order the keys of the dictionary should be processed in the output. If one assumes reverse sorting order, you can do this trivially with itertools.product():

from itertools import product

combinations = product(*(['{0}{1}'.format(v, i) for i in range(dictElement[v])] 
                         for v in sorted(dictElement, reverse=True))

Demo:

>>> from itertools import product
>>> dictElement = {"PA":2,"PB":2,"PC":3}
>>> combinations = product(*(['{0}{1}'.format(v, i) for i in range(dictElement[v])]
...                           for v in sorted(dictElement, reverse=True)))
>>> for combo in combinations:
...     print(combo)
...
('PC0', 'PB0', 'PA0')
('PC0', 'PB0', 'PA1')
('PC0', 'PB1', 'PA0')
('PC0', 'PB1', 'PA1')
('PC1', 'PB0', 'PA0')
('PC1', 'PB0', 'PA1')
('PC1', 'PB1', 'PA0')
('PC1', 'PB1', 'PA1')
('PC2', 'PB0', 'PA0')
('PC2', 'PB0', 'PA1')
('PC2', 'PB1', 'PA0')
('PC2', 'PB1', 'PA1')
Comments