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

39 Answered Questions

[SOLVED] How to make a flat list out of list of lists?

22 Answered Questions

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

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

9 Answered Questions

[SOLVED] Converting integer to string in Python?

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

11 Answered Questions

[SOLVED] Use of *args and **kwargs

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

28 Answered Questions

[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
  • 28 Answer
  • Tags:   python list

15 Answered Questions

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

33 Answered Questions

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

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

24 Answered Questions

[SOLVED] Difference between append vs. extend list methods in 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
  • 296238 View
  • 530 Score
  • 26 Answer
  • Tags:   python python-2.x

Sponsored Content