Thursday, 15 January 2015

python: combination of lists in dict, with various size of list -



python: combination of lists in dict, with various size of list -

five params can have various len (including empty). wrote long code first 3 params, more params icrement bigger code repeats. how minimize code?

params1 = [1,2] params2 = [] params3 = [3,4,5,6] # ... params5 = [7,8] # 3 params example: summary = {} if 0 < len(params1): param1 in params1: summary['param1'] = param1 if 0 < len(params2): param2 in params2: summary['param2'] = param2 if 0 < len(params3): param3 in params3: summary['param3'] = param3 print summary else: print summary else: if 0 < len(params3): param3 in params3: summary['param3'] = param3 print summary else: print summary else: if 0 < len(params2): param2 in params2: summary['param2'] = param2 if 0 < len(param3): param3 in params3: summary['param3'] = param3 print summary else: print summary else: if 0 < len(params3): param3 in params3: summary['param3'] = param3 print summary else: print summary

need dict combinations non empty params, output of illustration code:

{'param3': 3, 'param1': 1} {'param3': 4, 'param1': 1} {'param3': 5, 'param1': 1} {'param3': 6, 'param1': 1} {'param3': 3, 'param1': 2} {'param3': 4, 'param1': 2} {'param3': 5, 'param1': 2} {'param3': 6, 'param1': 2}

how replace illustration code smallest lines?

you can using recursion :

def affich(params, summary = none): #print(params, summary ) if len(params) == 0: print summary else: if summary none: summary = {} name, pars = params[0] if len(pars) == 0: affich(params[1:], summary ) else: p in pars: cur[name] = p affich(params[1:], summary ) affich((('params1', [1, 2]), ('params2', []), ('params3', [3, 4, 5, 6]), ('params5', [7, 8]))

gives :

{'params5': 7, 'params1': 1, 'params3': 3} {'params5': 8, 'params1': 1, 'params3': 3} {'params5': 7, 'params1': 1, 'params3': 4} {'params5': 8, 'params1': 1, 'params3': 4} {'params5': 7, 'params1': 1, 'params3': 5} {'params5': 8, 'params1': 1, 'params3': 5} {'params5': 7, 'params1': 1, 'params3': 6} {'params5': 8, 'params1': 1, 'params3': 6} {'params5': 7, 'params1': 2, 'params3': 3} {'params5': 8, 'params1': 2, 'params3': 3} {'params5': 7, 'params1': 2, 'params3': 4} {'params5': 8, 'params1': 2, 'params3': 4} {'params5': 7, 'params1': 2, 'params3': 5} {'params5': 8, 'params1': 2, 'params3': 5} {'params5': 7, 'params1': 2, 'params3': 6} {'params5': 8, 'params1': 2, 'params3': 6}

python list dictionary combinations

No comments:

Post a Comment