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... > One solution:
l=[['a', '13'], ['a', '3'], ['b', '6'], ['c', '12'], ['c', '15'], ['c','4'], ['d', '2'], ['e', '11'], ['e', '5'], ['e', '16'], ['e', '7']] d={} for k, v in l: if d.has_key(k): d[k].append(v) else: d[k]=[v] print "d=", d l=[x for x in d.items()] print l -Larry -- http://mail.python.org/mailman/listinfo/python-list