[Solved] Python create list combination


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')

4

solved Python create list combination