+ 9

group data with python

given an 2dList [[oma,50],[HonFu, 20],[oma,20]] I need a short hack for beginner to make it [[oma,70],[HonFu, 20]] maybe also with numpy or pandas

5th Mar 2020, 6:20 PM
Oma Falk
Oma Falk - avatar
10 Answers
5th Mar 2020, 7:28 PM
Russ
Russ - avatar
+ 6
items = [["oma", 50], ["HonFu", 20], ["oma", 20]] d = {item[0] : 0 for item in items} for item in items: d[item[0]] += item[1] items = [[k, v] for k,v in d.items()] print(items)
5th Mar 2020, 9:00 PM
andriy kan
andriy kan - avatar
+ 6
If using dictionary; lst = [['Oma', 50], ['Honfu', 50], ['Oma', 20]] dct = {} for i in lst: dct[i[0]] = i[1] + dct.get(i[0], 0) print(*dct.items())
5th Mar 2020, 9:35 PM
Russ
Russ - avatar
+ 5
no hack, done with only python module: from collections import Counter lst = [['oma',50], ['honfu',20], ['oma',20], ['honfu',17]] print("input list : ", lst) res = list(Counter(key for key, num in lst for _ in range(num)).items()) print("aggregated list : ", res) # output: [('oma', 70), ('honfu', 37)]
5th Mar 2020, 8:16 PM
Lothar
Lothar - avatar
+ 4
Here an other version, just with dict.update lst = [['oma',50], ['honfu',20], ['oma',20], ['honfu',7]] dict = {} for i in lst: dict.update({i[0]:i[1]+dict.get(i[0])}) if dict.get(i[0]) else dict.update({i[0]:i[1]}) print(dict)
5th Mar 2020, 9:13 PM
Lothar
Lothar - avatar
+ 2
Not sure if that meets the requirements "for beginner" but I had to make a oneliner challenge out of it 😂 https://code.sololearn.com/cjfFvOPoraBh/?ref=app
7th Mar 2020, 9:02 AM
Martin MĂśhle
Martin MĂśhle - avatar
+ 2
https://www.sololearn.com/post/1429641/?ref=app
17th Dec 2021, 5:57 AM
✓`•°`™AnOnimus™`°•`✓ فايز الله‎
✓`•°`™AnOnimus™`°•`✓   فايز الله‎ - avatar
+ 1
Just another variant with defaultdict https://code.sololearn.com/cx3dnPKTG7FN/?ref=app
6th Mar 2020, 8:26 PM
Tibor Santa
Tibor Santa - avatar
0
Haw many possible
7th Mar 2020, 9:22 AM
H.M Mizanur Rahman
H.M Mizanur Rahman - avatar