I have an array which looks like this:
array1 = [[4000,"Mark",5],[4100,"George",3],[4000,"Mark",2],[4200,"Steve",4],[4100,"George",2],[4000,"Mark",1]]
I'm wondering how I can reformat this array to look like this:
array2 = [[4000,"Mark",[5,2,1]],[4100,"George",[3,2]],[4200,"Steve",4]]
You can use an ordered dictionary (collections.OrderedDict) to store the first 2 items as key and the common numbers in a list as values:
>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> for i,j,k in array1:
... d.setdefault((i,j),[]).append(k)
...
>>> [[i,j,k] for (i,j),k in d.items()]
[[4000, 'Mark', [5, 2, 1]], [4100, 'George', [3, 2]], [4200, 'Steve', [4]]]
[a+[[c[-1] for c in b]] for a,b in itertools.groupby(operator.itemgetter(0,1),sorted(array1))]
I guess ... i doubt this is gonna help you learn anything ... a more appropriate place to ask for help if you dont even know where to start, is in class (ask your teacher or classmates) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With