sam smith
sam smith

Reputation: 29

Sum space-separated integers as string in a list

I currently have this list: ['5 4 7', '4 3 1', '6 8 4'', '4 8 6'] Note that not all numbers are separated by commas.

I would like to be able to calculate the total for each section of the list. For example, the first calculation should be 5+4+7 to give me 16. I would just like to know how to convert this list to be able to do maths calculations with the numbers.

Upvotes: 2

Views: 1036

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140196

split your strings, map to integer and perform sum on the resulting inputs, in a list comprehension:

>>> [sum(map(int,x.split())) for x in ['5 4 7', '4 3 1', '6 8 4', '4 8 6']]
[16, 8, 18, 18]

(works for negative values as well :))

Upvotes: 4

Ajax1234
Ajax1234

Reputation: 71461

You can also use regex:

import re
s = ['5 4 7', '4 3 1', '6 8 4', '4 8 6']
new_s = [sum(map(int, re.findall('\d+', b))) for b in s]

Output:

[16, 8, 18, 18]

However, if every digit is a single character, then you can use isdigit():

last_result = [sum(map(int, filter(lambda x:x.isdigit(), i))) for i in s]

Upvotes: 0

Related Questions