How to sum elements of a list encoded as strings with numbers

Question:

There is a list with duplicate word elements with a number at the end of them. I want to sum the duplicate’s numbers, remove the duplicates and print words with sum of numbers but I don’t know how…

Input:

a = ["mango3", "apple2", "kiwi1", "kiwi2", "mango2"]

Output:

mango5
apple2
kiwi3
Asked By: luna

||

Answers:

Here’s a solution, first using regex to split the fruit/numbers in your list’s elements, building a dictionary of fruit:total_number pairs, and finally recreating a list from the dictionary:

import re
a=["mango3","apple2","kiwi1","kiwi2","mango2"]
b={}
for element in a:
    fruit, number = re.findall('D+',element)[0], re.findall('d+', element)[0]
    b[fruit] = b.get(fruit,0) + int(number)
c=[fruit + str(number) for fruit,number in b.items()]

print(c)
# ['mango5', 'apple2', 'kiwi3']

Explanation about the regex: d stands for digit, so d+ will return (in this case where there’s only one digit sequence) the longest succession of (at least 1) digits; similarly, D stands for non-digit.

Note that you could use a single regex with catching groups this way:

fruit, number = re.findall('(D+)(d+)', element)[0]
Answered By: Swifty
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.