Python Forum
How to separate the values in an element to add them
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to separate the values in an element to add them
#5
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.
Larz60+ likes this post
Reply


Messages In This Thread
RE: How to separate the values in an element to add them - by deanhystad - Jan-23-2023, 04:28 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  importing functions from a separate python file in a separate directory Scordomaniac 3 1,465 May-17-2022, 07:49 AM
Last Post: Pedroski55
  Unable to locate element no such element gahhon 6 4,636 Feb-18-2019, 02:09 PM
Last Post: gahhon
  Looping through dictionary and comparing values with elements of a separate list. Mr_Keystrokes 5 4,010 Jun-22-2018, 03:08 PM
Last Post: wavic
  Comparing values in separate lists KaleBosRatjes 3 3,131 May-02-2018, 04:38 PM
Last Post: KaleBosRatjes
  Change single element in 2D list changes every 1D element AceScottie 9 12,250 Nov-13-2017, 07:05 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020