Home > database >  Need string output with combination on integers
Need string output with combination on integers

Time:01-03

I have a dictionary, with 'int' as keys

{12: '2012-Q1', 13: '2014-Q2', 14: '2017-Q2', 15: '2019-Q3'}

and I am trying to create a string for each possible combination for 12, 13, 14, 15. The string should look start from 'Gen'

['Gen_12_13',
 'Gen_12_14',
 'Gen_12_15',
 'Gen_13_14',
 'Gen_13_15',
 'Gen_14_15',
 'Gen_12_13_14',
 'Gen_12_13_15',
 'Gen_12_14_15',
 'Gen_13_14_15',
 'Gen_12_13_14_15']

I used the 'combination' function to get all the combinations first and then tried to iterate through it to create the 'Gen' string.

dict_gens = {12: '2012-Q1', 13: '2014-Q2', 14: '2017-Q2', 15: '2019-Q3'}
all_gens = list(dict_gens.keys())
list_comb = list()
name_comb = list()
counter = 0

for item in range(2, len(all_gens) 1):
    combs = combinations(all_gens, item)
    for comb in combs:
        list_comb.append(comb)
        
for comb in list_comb:
    if counter <= len(comb):
        for comb_item in comb:
#             print(comb_item)
            name = '_'   str(comb_item)
            counter =1
        name_comb.append('Gen' name)

CodePudding user response:

The itertools.combinations part looks right, but the loop where you're building the final strings looks unnecessarily complex; just use str.join to join the combinations into the desired strings.

>>> gens = {12: '2012-Q1', 13: '2014-Q2', 14: '2017-Q2', 15: '2019-Q3'}
>>> from itertools import combinations
>>> ["Gen_"   "_".join(map(str, c)) for n in range(len(gens) - 1) for c in combinations(gens, n 2)]
['Gen_12_13', 'Gen_12_14', 'Gen_12_15', 'Gen_13_14', 'Gen_13_15', 'Gen_14_15', 'Gen_12_13_14', 'Gen_12_13_15', 'Gen_12_14_15', 'Gen_13_14_15', 'Gen_12_13_14_15']
  • Related