Python Forum
How to separate the values in an element to add them - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to separate the values in an element to add them (/thread-39260.html)



How to separate the values in an element to add them - monty024 - Jan-23-2023

Greetings,

I have a python question.. I have a list with the following four elements.
What I want to do is add the vales in element 1 (17,21,29,35,36) to get the sum (138)
The area I am having the problem is how add the numbers in that element?
The numbers are all part of element 1, how would I separate them in to integers so I can add them to get the sum?

Here is an example of a list.
['01/21/2023', '17,21,29,35,36', '1,E','37.43']

Any help or guidance would be greatly appreciated.

Regards,
Monty


RE: How to separate the values in an element to add them - rob101 - Jan-23-2023

This would be one way:

the_list = ['01/21/2023', '17,21,29,35,36', '1,E', '37.43']

numbers = the_list[1].split(',')
total = 0

for number in numbers:
    total += int(number)

print(total)
Or, you could do that directly:

the_list = ['01/21/2023', '17,21,29,35,36', '1,E', '37.43']
total = 0
for number in the_list[1].split(','):
    total += int(number)
print(total)



RE: How to separate the values in an element to add them - monty024 - Jan-23-2023

Wow!! Thank you Rob101! I spent a week trying to figure this out.. I was close.
I was using the split but I was getting the comma between each value..


RE: How to separate the values in an element to add them - rob101 - Jan-23-2023

(Jan-23-2023, 01:04 AM)monty024 Wrote: Wow!! Thank you Rob101!

You're welcome; pleased to help.

Yet another way, I just thought of:
the_list = ['01/21/2023', '17,21,29,35,36', '1,E', '37.43']

int_numbers = []
for number in the_list[1].split(','):
    int_numbers.append(int(number))

print(sum(int_numbers))
Edit to add: it depends on what you want to do with the numbers. If you want to use them later on, then maybe use my 3rd way, as you'll have a list object that holds said numbers, but if all you want is the total, then there's little point in creating an object to hold them.


RE: How to separate the values in an element to add them - deanhystad - Jan-23-2023

Lots of ways to do this. Here are a 3 more.
from functools import reduce

values = '1,2,3,4,5'

print(sum(int(n) for n in values.split(',')))
print(sum(map(int, values.split(','))))
print(reduce(lambda a, b: a + int(b), values.split(','), 0))
I presented the choices in my order of preference. Comprehensions are very useful and something you need to know how to use. map() is like a one-trick-pony version of a comprehension. I don't find reduce() very useful.