On 22/06/2010 15:06, Neil Webster wrote:
Hi all,
I've got a simple problem but it's defeated me and I was wondering if
somebody could point out where I'm going wrong or offer an alternative
solution to the problem?
I have a list of lists such as [[a,2,3,4],[b,10,11,12], [a,2,3,4]]. I
need to combine the two lists that have the same first character in
this example 'a'. In reality there are 656 lists within the list.
My attempt so far is:
L = [[a,2,3,4],[b,10,11,12], [a,2,3,4]]
d = []
z = 1
while z<= len(L):
for a in L:
if L.count(a[0])> 1:
d.append(a[2:])
summed = [sum(pair) for pair in zip(d[0], d[1])]
z = z+1
print summed
Any pointers more than welcome.
Thanks all.
My simplistic approach.
Sort the list (this happens in place).
Use the itertools groupby function to place everything together, see
http://docs.python.org/library/itertools.html?highlight=groupby#itertools.groupby
Combine the lists in the groups.
HTH.
Mark Lawrence.
--
http://mail.python.org/mailman/listinfo/python-list