lists and dictionaries

Bart Ogryczak B.Ogryczak at gmail.com
Thu Jul 12 16:20:11 CEST 2007


On 12 jul, 04:49, anethema <jefish... at gmail.com> wrote:
> > li =  [ {'index': 0, 'transport': 'udp', 'service_domain':
> > 'dp0.example.com'},
> >         {'index': 1, 'transport': 'udp', 'service_domain':
> > 'dp1.example.com'},
> >         {'index': 0, 'transport': 'tcp', 'service_domain':
> > 'dp0.example.com'},
> >         {'index': 1, 'transport': 'tcp', 'service_domain':
> > 'dp1.example.com'}]
>
> I like this solution:
>
> [{ 'transports'    : [d['transport'] for d in li if
> d['service_domain'] == dom],
>    'service_domain': dom,
>  } for dom in set(d2['service_domain'] for d2 in li)]
>
> merely because it takes one line.  Humorously enough, it appears to be
> twice as efficient,

Correct me if I´m wrong, that is a O(n**2) solution, to O(n) problem.




More information about the Python-list mailing list