Another way:
from collections import defaultdict
x = [['cat', 'NM123', 12], ['cat', 'NM234', 12], ['dog', 'NM56', 65]]
y = [['cat', 'NM123, NM234', 12], ['dog', 'NM56', 65]]
def f(acc, x):
acc[(x[0], x[2])] += [x[1]]
return acc
assert y == [[k[0], ', '.join(v), k[1]] for k, v in reduce(
long but this too works :)
>>> p=[]
>>> x=[['cat','NM123',12],['cat','NM234',12], ['dog', 'NM56',65]]
>>> import copy
>>> def fn(a,b):
if len(a)==3 and a[0]==b[0] and a[-1]==b[-1] and a[1]!=b[1]:
a.insert(-1,b[1])
p.append(a)
else:
p.append(b)
return p
>>> reduce(fn, copy.deepcopy(x))
[['cat', 'N
from itertools import groupby
x = [['cat','NM123',12],['cat','NM234',12], ['dog', 'NM56',65]]
y = [['cat','NM123, NM234', 12], ['dog', 'NM56', 65]]
def grouper(t) : return (t[0],t[2])
assert y == list(list((keys[0],", ".join(val[1] for val in vals),keys[1]))
for keys, vals in g
One thing is here:
The x[0] and x[1] are in union with each other.
this needs to be solved by set operations on list of lists.
On Thu, Dec 5, 2013 at 1:55 PM, Vikram K wrote:
> Any suggestions on what i have to do to go from x to y?
>
> >>> x = [['cat','NM123',12],['cat','NM234',12], ['dog'