Home > Enterprise >  Combination of Keys with Empty Tuple
Combination of Keys with Empty Tuple

Time:07-02

I have a dictionary with keys. The keys are tuple of two.

dict_keys([(), ('cHW',), ('cHWtil',), ('cHW', 'cHW'), ('cHWtil', 'cHWtil'),('cHW', 'cHWtil'))

However the tuple can also be a combination of a string and an empty element.

If I want to create the same keys by using iterables.product I am not sure how I can get the same keys, because I can't produce the keys in which there is only one string and comma nothing like in the dictionary keys above.

For example if I write the following I get:

coefficients=[(), ('cHW'), ('cHWtil')]
coefficient_combinations=itertools.product(coefficients, repeat=2)
list(coefficient_combinations)
[((), ()),
 ((), 'cHW'),
 ((), 'cHWtil'),
 ('cHW', ()),
 ('cHW', 'cHW'),
 ('cHW', 'cHWtil'),
 ('cHWtil', ()),
 ('cHWtil', 'cHW'),
 ('cHWtil', 'cHWtil')]

Which doesn't for example contain the first key in the list I showed at the beginning, because I get these brackets.

CodePudding user response:

What you're looking for is combinations_with_replacement().

Then, for loop on the size like so:

>>> coefficients=['cHW', 'cHWtil']
>>> combs = itertools.chain.from_iterable(itertools.combinations_with_replacement(coefficients, i) for i in range(3))
>>> list(combs)
[(), ('cHW',), ('cHWtil',), ('cHW', 'cHW'), ('cHW', 'cHWtil'), ('cHWtil', 'cHWtil')]

If what you're actually looking for is the powerset, please see this answer.


Alternative implementation:

combs = [c for i in range(3) for c in itertools.combinations_with_replacement(coefficients, i)]

I prefer the top, but up to you.

  • Related