Reputation: 61
In order to simplify the reading of information for all other users, I would like to reduce a nested list where names appear in duplicate. Concrete example:
[['savoielibrercgcm', '0.25'], ['MeriFer', '0.25'], ['XlassII', '0.25'], ['Tomixt_31', '0.25'], ['Tomixt_31', '0.25'], ['Tomixt_31', '0.25']]
(The value is not always equal to 0.25)
The ideal would be to be able to add the content according to the nickname to obtain a list like this:
[['savoielibrercgcm', '0.25'], ['MeriFer', '0.25'], ['XlassII', '0.25'], ['Tomixt_31', '0.75']]
I could easily do it with a for loop and an if condition. But the program being heavy and having to manage data in great quantity, I would like to be able to "optimize" this code. I tried to go through a conversion to dict but that removes duplicate keys.
Do you have any ideas ? of the map? I must admit that I have never touched the map() :/
Thanks in advance for the help ^^'
Upvotes: 1
Views: 403
Reputation: 26998
You could do this using an intermediate dictionary like this:
from collections import defaultdict
mydict = defaultdict(int)
mylist = [['savoielibrercgcm', '0.25'], ['MeriFer', '0.25'], ['XlassII', '0.25'], ['Tomixt_31', '0.25'], ['Tomixt_31', '0.25'], ['Tomixt_31', '0.25']]
for name, value in mylist:
mydict[name] += float(value)
newlist = [[k, f'{v:.2f}'] for k, v in mydict.items()]
print(newlist)
Output:
[['savoielibrercgcm', '0.25'], ['MeriFer', '0.25'], ['XlassII', '0.25'], ['Tomixt_31', '0.75']]
Upvotes: 0
Reputation: 42143
Using an dictionary to group the names should work for this:
L = [['savoielibrercgcm', 0.25], ['MeriFer', 0.25], ['XlassII', 0.25],
['Tomixt_31', 0.25], ['Tomixt_31', 0.25], ['Tomixt_31', 0.25]]
grouped = dict()
grouped.update((name,grouped.get(name,0)+value) for name,value in L)
L = [*map(list,grouped.items())]
print(L)
[['savoielibrercgcm', 0.25], ['MeriFer', 0.25], ['XlassII', 0.25],
['Tomixt_31', 0.75]]
Note: I assumed you don't really want your numerical values to be stored as strings
Upvotes: 0
Reputation: 456
Here's a solution using collections.Counter
:
from collections import Counter
c = Counter()
for name, value in inputs:
c[name] += float(value)
then you can convert the accumulated values for the name to string again. Counter works just like the built-in dict
. I'm not sure if your task can be accomplished in a more performant way.
Upvotes: 1