Python list in reformatted list

What is the pythonic way to reorganize my next data?

I have data

data = [
        ['a','b',1], ['a','b',2], ['a','b',3],
        ['a','c',3], ['a','c',4],
        ['f','g',2], ['f','g',5], ['f','g',9]
       ]

And I want to rearrange it in the following format:

data = [
        ['a', 'b', 1, 2, 3], 
        ['a', 'c', 3, 4], 
        ['f', 'g', 2, 5, 9]
       ]

So basically these two first elements in each internal list are a way to distinguish different elements, and the next number is data. I want to have only one row for each element that contains all the data.

+4
source share
2 answers
import collections

keyed = collections.defaultdict(list) # (a,b): [1,2,3]

for k1,k2,val in data:
    keyed[(k1,k2)].append(val)

[list(keys) + vals for keys,vals in sorted(keyed.items())]
+4
source

, , dict:

, OrderedDict , .

>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> 
>>> for i, j, k in data:
...     d.setdefault((i, j), []).append(k)
... 
>>> [[i,j] + k for (i,j), k in d.items()]
[['a', 'b', 1, 2, 3], ['a', 'c', 3, 4], ['f', 'g', 2, 5, 9]]

, groupby chain itertools, :

>>> from itertools import groupby, chain
>>> from operator import itemgetter
>>> from collections import OrderedDict

>>> [OrderedDict.fromkeys(chain.from_iterable(g)).keys() for _,g in groupby(data, key=itemgetter(0, 1))]
[['a', 'b', 1, 2, 3], ['a', 'c', 3, 4], ['f', 'g', 2, 5, 9]]
+1

All Articles