+ 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
10 Answers
+ 10
Based on this answer:
https://stackoverflow.com/a/38648218
https://code.sololearn.com/cCHGrz92f99M/?ref=app
+ 8
Is this a 'hack'?
https://code.sololearn.com/cRm1573u2GNy/?ref=app
+ 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)
+ 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())
+ 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)]
+ 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)
+ 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
+ 2
https://www.sololearn.com/post/1429641/?ref=app
+ 1
Just another variant with defaultdict
https://code.sololearn.com/cx3dnPKTG7FN/?ref=app
0
Haw many possible