By sam smith


2018-03-13 15:47:04 8 Comments

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.

2 comments

@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]

Related Questions

Sponsored Content

36 Answered Questions

[SOLVED] Making a flat list out of list of lists in Python

23 Answered Questions

[SOLVED] Difference between append vs. extend list methods in Python

26 Answered Questions

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

  • 2008-10-07 01:39:38
  • Eugene M
  • 2701639 View
  • 2334 Score
  • 26 Answer
  • Tags:   python list

32 Answered Questions

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

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 2580246 View
  • 2928 Score
  • 32 Answer
  • Tags:   python directory

27 Answered Questions

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

  • 2008-09-10 06:20:11
  • Ray Vega
  • 1821136 View
  • 2818 Score
  • 27 Answer
  • Tags:   python list is-empty

14 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

10 Answered Questions

[SOLVED] Converting integer to string in Python?

  • 2009-06-07 10:22:38
  • Hick
  • 2566342 View
  • 1027 Score
  • 10 Answer
  • Tags:   python

16 Answered Questions

[SOLVED] Convert bytes to a string?

26 Answered Questions

[SOLVED] How to print number with commas as thousands separators?

  • 2009-11-30 23:11:43
  • Elias Zamaria
  • 274164 View
  • 503 Score
  • 26 Answer
  • Tags:   python python-2.x

11 Answered Questions

[SOLVED] *args and **kwargs?

  • 2010-08-03 08:28:07
  • MacPython
  • 766820 View
  • 1214 Score
  • 11 Answer
  • Tags:   python args kwargs

Sponsored Content