algorizm to merge nodes

JD Jiandong.Ge at gmail.com
Fri Oct 17 16:52:24 EDT 2008


Hi,

Thanks for the help,

but the result is not quite right:

[['a', 'b', 'g'], ['c', 'd', 'u'], ['b', 'p'], ['e', 'f', 'k']]

the ['b', 'p'] is not merged.

JD

On Oct 17, 2:35 pm, "Chris Rebert" <c... at rebertia.com> wrote:
> (Disclaimer: completely untested)
>
> from collections import defaultdict
>
> merged = defaultdict(list)
> for key, val in your_list_of_pairs:
>     merged[key].append(val)
>
> result = [[key]+vals for key, vals in merged.items()]
>
> Cheers,
> Chris
> --
> Follow the path of the Iguana...http://rebertia.com
>
> On Fri, Oct 17, 2008 at 1:20 PM, JD <Jiandong... at gmail.com> wrote:
> > Hi,
>
> > I need help for a task looks very simple:
>
> > I got a python list like:
>
> > [['a', 'b'], ['c', 'd'], ['e', 'f'], ['a', 'g'], ['e', 'k'], ['c',
> > 'u'], ['b', 'p']]
>
> > Each item in the list need to be merged.
>
> > For example, 'a', 'b' will be merged, 'c', 'd' will be merged.
>
> > Also if the node in the list share the same name, all these nodes need
> > be merged.
>
> > For example, ['a', 'b'], ['a', 'g'] ['b', 'p'] will be merged to ['a',
> > 'b', 'g', 'p']
>
> > The answer should be:
>
> > [['a', 'b', 'g', 'p'], ['c', 'd', 'u'], ['e', 'f', 'k']]
>
> > Anyone has a solution?
>
> > Thanks,
>
> > JD
> > --
> >http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list