#### [SOLVED] 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.

#### @Jean-François Fabre 2018-03-13 15:50:59

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 :))

#### @sam smith 2018-03-13 15:58:58

Yes thank you. I was trying to do it in that method after searching around but I kept getting errors.

#### @Ajax1234 2018-03-13 15:58:12

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]

### [SOLVED] How do I list all files of a directory?

• 2010-07-08 19:31:22
• duhhunjonn
• 2796955 View
• 3123 Score
• Tags:   python directory

### [SOLVED] Converting integer to string in Python?

• 2009-06-07 10:22:38
• Hick
• 2733024 View
• 1096 Score
• Tags:   python

### [SOLVED] Use of *args and **kwargs

• 2010-08-03 08:28:07
• MacPython
• 782729 View
• 1246 Score
• Tags:   python args kwargs

### [SOLVED] Finding the index of an item given a list containing it in Python

• 2008-10-07 01:39:38
• Eugene M
• 2936670 View
• 2435 Score
• Tags:   python list

### [SOLVED] How do I check if a list is empty?

• 2008-09-10 06:20:11
• Ray Vega
• 1956983 View
• 2969 Score
• Tags:   python list