loop over list and process into groups

nn pruebauno at latinmail.com
Fri Mar 5 11:41:24 EST 2010



mk wrote:
> 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

Oh my! You could have at least used some "if else" to make it a little
bit easier on the eyes :-)

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



More information about the Python-list mailing list