I have a sequence is like this,
seq = [[["A","AA","AB"],[0,1,2,3]], [["B","BB","BC"],[1,2,3]], [["C","CA","CB"],[0,1,2,3]]]
I wanted to convert this to something like below
[[['A', 'AA', 'AB', 'C', 'CA', 'CB'], [0, 1, 2, 3]], [['B', 'BB', 'BC'], [1, 2, 3]]]
I tried but I am getting like below. Can someone help in achieving the correct results.
In [105]: from itertools import groupby ...: from operator import itemgetter ...: seq = [[["A","AA","AB"],[0,1,2,3]], [["B","BB","BC"],[1,2,3]], [["C","CA","CB"],[0,1,2,3]]] ...: seq.sort(key = itemgetter(1)) ...: groups = groupby(seq, itemgetter(1)) ...: [[(item[0],key) for item in data] for (key, data) in groups] Out[105]: [[(['A', 'AA', 'AB'], [0, 1, 2, 3]), (['C', 'CA', 'CB'], [0, 1, 2, 3])], [(['B', 'BB', 'BC'], [1, 2, 3])]]
Advertisement
Answer
In [105]: from itertools import groupby ...: from operator import itemgetter ...: seq = [[["A","AA","AB"],[0,1,2,3]], [["B","BB","BC"],[1,2,3]], [["C","CA","CB"],[0,1,2,3]]] ...: seq.sort(key = itemgetter(1)) ...: groups = groupby(seq, itemgetter(1)) ...: l = [[(item[0],key) for item in data] for (key, data) in groups] ...: for i in l: ...: flat_list = [item for sublist in i[0] for item in sublist] ...: i[0] = flat_list