Answer the question
In order to leave comments, you need to log in
How to stack multiple identical elements in a list?
There is a list:
We need a program that will add the same elements into one. That is, for example, if you look at the list above, you should get the following:
It looks like a principle in mathematics, like the principle of addition of similar ones. It's about the same here. That is, the program itself must look through the elements of the list and, when finding the same, adds the numbers to another larger number, and leaves the letter the same.
mylist = ["8A", "4R", "2A", "3H", "7R"]
mylistNew = ["10A", "11R", "3H"]
Answer the question
In order to leave comments, you need to log in
def sum_items(arr):
result = {}
for item in arr:
v, k = int(item[:-1]), item[-1]
result[k] = result.get(k, 0) + v
return [ str(v) + k for k, v in result.items() ]
from collections import defaultdict
from functools import reduce
a = ["8A", "4R", "2A", "3H", "7R"]
x = [str(v) + k for k, v in reduce(lambda acc, v: acc.update({v[0]: acc[v[0]] + v[1]}) or acc,
((i[-1], int(i[:-1])) for i in a),
defaultdict(int)).items()]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question