loop over list and process into groups

mk mrkafk at gmail.com
Fri Mar 5 14:26:13 CET 2010


Sneaky Wombat wrote:
> [ 'VLAN4065',
>  'Interface',
>  'Gi9/6',
>  'Po2',
>  'Po3',
>  'Po306',
>  'VLAN4068',
>  'Interface',
>  'Gi9/6',
>  'VLAN4069',
>  'Interface',
>  'Gi9/6',]

Hey, I just invented a cute ;-) two-liner using list comprehensions:

# alist = list above

tmp, dk = [], {}
[(x.startswith('VLAN') and (dk.setdefault(x,[]) or tmp.append(x))) or 
(not x.startswith('VLAN') and dk[tmp[-1]].append(x))    for x in alist 
if x != 'Interface']

No need to use a nuke like itertools to kill a fly. ;-)

Regards,
mk




More information about the Python-list mailing list