newbie/ merging lists of lists with items in common

James Stroud jstroud at mbi.ucla.edu
Fri Feb 2 15:50:52 EST 2007


ardief 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...
> 


Did someone suggest this? I couldn't find it and it seems simplest to me 
(no imports, etc.):

keys = sorted(set(i[0] for i in alist))
d = [(k,[i[1] for i in alist if i[0]==k]) for k in keys]

E.g.:
py> alist = [['a', '13'],
...          ['a', '3'],
...          ['b', '6'],
...          ['c', '12'],
...          ['c', '15'],
...          ['c', '4'],
...          ['d', '2'],
...          ['e', '11'],
...          ['e', '5'],
...          ['e', '16'],
...          ['e', '7']]
py> keys = sorted(set(i[0] for i in alist))
py> d = [(k,[i[1] for i in alist if i[0]==k]) for k in keys]
py> d

[('a', ['13', '3']),
  ('b', ['6']),
  ('c', ['12', '15', '4']),
  ('d', ['2']),
  ('e', ['11', '5', '16', '7'])]



James



More information about the Python-list mailing list