Generating multiple lists from one list

Pierre Quentel quentel.pierre at wanadoo.fr
Wed Jul 5 14:18:16 EDT 2006


# first step : build a dictionary mapping the objects
# to all possible ids

alist = ['a.1','b.3','b.4','c.2','c.6','d.3']
elts = {}
for item in alist:
    obj=item.split('.')[0]
    if elts.has_key(obj):
        elts[obj].append(item)
    else:
        elts[obj] = [item]

# then build the Python code that will iterate
# on all the possible values

ks = elts.keys()
ks.sort()

p_code = ''
for i,k in enumerate(ks):
    p_code += i*' ' + "for item%s in elts['%s']:\n" %(i,k)
p_code += len(ks)*' '+'print ['+','.join([ "item%s" %i
    for i,k in enumerate(ks) ])+']'

# print the code
print p_code

>for item0 in elts['a']:
> for item1 in elts['b']:
>  for item2 in elts['c']:
>   for item3 in elts['d']:
>    print [item0,item1,item2,item3]

# execute this code
exec p_code

>['a.1', 'b.3', 'c.2', 'd.3']
>['a.1', 'b.3', 'c.6', 'd.3']
>['a.1', 'b.4', 'c.2', 'd.3']
>['a.1', 'b.4', 'c.6', 'd.3']

It works, but there are probably more elegant ways to do it

Just a question : in your message you say that 'a.1' and 'b.1' can not
exist together, but in the example there are lists with both 'b.3' and
'd.3' : should such lists be filtered ?

Regards,
Pierre




More information about the Python-list mailing list