newbie/ merging lists of lists with items in common

Laurent Pointal laurent.pointal at limsi.fr
Fri Feb 2 09:46:48 EST 2007


ardief a écrit :
> 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...
> 

You may take a look to the groupby iterator in the standard itertools
module.

http://docs.python.org/lib/itertools-functions.html



More information about the Python-list mailing list