Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group list of lists in Python?

Tags:

python

list

I have a list of lists looking like this:

['user1', time, cpus, mem]  
['user1', time, cpus, mem]
['user2', time, cpus, mem]
['user3', time, cpus, mem]

and so on..

I need just one list per user with time, cpus and mem added together. I've tried a few things but i cant make it work.

like image 957
Jamal 'kRUSER' Benson Avatar asked Apr 23 '18 07:04

Jamal 'kRUSER' Benson


People also ask

How do you Groupby a list in Python?

You can group DataFrame rows into a list by using pandas. DataFrame. groupby() function on the column of interest, select the column you want as a list from group and then use Series. apply(list) to get the list for every group.

Can you have a list of list of lists in Python?

We can have a list of many types in Python, like strings, numbers, and more. Python also allows us to have a list within a list called a nested list or a two-dimensional list.

How do you concatenate a list of lists in Python?

You can concatenate multiple lists into one list by using the * operator. For Example, [*list1, *list2] – concatenates the items in list1 and list2 and creates a new resultant list object. Usecase: You can use this method when you want to concatenate multiple lists into a single list in one shot.


2 Answers

A sweet, Pythonic and concise way to do that would be:

from collections import defaultdict

l = [                  
    ['user1', 0, 1, 0],                                                    
    ['user2', 2, 2, 2],      
    ['user3', 2, 2, 1],
    ['user3', 1, 1, 2],
    ['user1', 1, 0, 1],
]


merged = defaultdict(lambda: [0, 0, 0])

for user, *values in l:               
     merged[user] = [sum(i) for i in zip(values, merged[user])]

Output:

In : merged
Out: 
defaultdict(<function __main__.<lambda>>,
        {'user1': [1, 1, 1], 'user2': [2, 2, 2], 'user3': [3, 3, 3]})

That uses a defaultdict with a list of length 3 as its default value. The relevant user's values are updated for each element in the list.

like image 200
etene Avatar answered Oct 20 '22 15:10

etene


You can do this using a dictionary in order to group list items by user.

Then just use zip function to find out the sum for every feature from time, cpus, mem list.

mylist = [['user1', 1, 6, 8], 
['user1', 2, 7, 9],
['user2', 3, 7, 5],
['user3', 4, 7, 3]]

dict = {}
for elem in mylist:
  if elem[0] not in dict:
    dict[elem[0]] = []
  dict[elem[0]].append(elem[1:])

for key in dict:
  dict[key] = [sum(i) for i in zip(*dict[key])]

Output

In[1]: dict
Out[1]: {'user1': [3, 13, 17], 'user2': [3, 7, 5], 'user3': [4, 7, 3]}
like image 35
Mihai Alexandru-Ionut Avatar answered Oct 20 '22 16:10

Mihai Alexandru-Ionut