Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping items in a list based on their contents

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]]
like image 313
Peter Avatar asked Dec 05 '25 11:12

Peter


2 Answers

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]]] 
like image 157
Mazdak Avatar answered Dec 07 '25 01:12

Mazdak


[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) ...

like image 44
Joran Beasley Avatar answered Dec 07 '25 01:12

Joran Beasley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!