newbie/ merging lists of lists with items in common

Paddy paddy3118 at netscape.net
Fri Feb 2 09:50:42 EST 2007


On Feb 2, 2:39 pm, "Paddy" <paddy3... at netscape.net> wrote:
> On Feb 2, 1:55 pm, "ardief" <rachele.defel... at gmail.com> wrote:
>
>
>
> > Hi everyone
> > Here is my problem:
> > I have a list that looks like this -
> > [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c',
> > '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
>
> > and I would like to end up with something like this, i.e. with the
> > only one list per letter:
>
> > [['a', ['13' '3']], ['b', '6'], ['c', ['12', '15', '4']], ['d', '2'],
> > ['e', ['11', '5', '16', '7']]]
>
> > I have the feeling it's trivial, and I've scoured the group archives -
> > sets might be a possibility, but I'm not sure how to operate on a list
> > of lists with sets.
>
> > This function also gives me what I want, more or less, but I don't
> > know how to make it run until it's covered all the possibilities, if
> > that makes sense...
>
> > def sigh(list):
> >         for a in list:
> >                 i = list.index(a)
> >                 if a != list[-1]:    ##if a is not the last one, i.e. there is a
> > next one
> >                         n = alist[i+1]
> >                         if a[0] == n[0]:
> >                                 a.append(n[1:])
> >                                 del alist[i+1]
>
> > Sorry about the lengthy message and thanks for your suggestions - I'm
> > trying to learn...
>
> : python
> Python 2.5 (r25:51908, Nov 28 2006, 16:10:01)
> [GCC 3.4.3 (TWW)] on sunos5
> Type "help", "copyright", "credits" or "license" for more information.>>> from pprint import pprint as pp
> >>> from collections import defaultdict
> >>> data = [['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c', '4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']]
> >>> d = defaultdict(list)
> >>> _ = [d[x0].append(x1) for x0,x1 in data]
> >>> pp(d)
>
> defaultdict(<type 'list'>, {'a': ['13', '3'], 'c': ['12', '15', '4'],
> 'b': ['6'], 'e': ['11', '5', '16', '7'], 'd': ['2']})>>> pp(sorted(d.items()))
>
> [('a', ['13', '3']),
>  ('b', ['6']),
>  ('c', ['12', '15', '4']),
>  ('d', ['2']),
>  ('e', ['11', '5', '16', '7'])]
>
>
>
> - Paddy


Use defaultdict(set) and d[x0].add(x1) if you also want to remove
duplicates.

- Paddy.




More information about the Python-list mailing list