I am trying to sum a list of "individual" elements in a list. I have seen a lot of posts using sum but these only sum the entire list not the individual numbers within the list. This is typically used in numerology and therefore needs to sum and resolve each element to it’s base 9 equivalent.
Current result:
numsum = [1, 23, 45, 76, 123]
output = sum(numsum)
print(output)
Output: 268
Required result:
output: [1, 5, 9, 4, 6]
I have tried using for loops but no real success. Anyone know what the most pythonic way to do this is?
>Solution :
It looks like you want to sum the digits of each number.
You could use an intermediate conversion to string within a list comprehension:
numsum = [1, 23, 45, 76, 123]
out = [sum(map(int, str(n))) for n in numsum]
A more numerical approach might be to use a repeated division by 10:
def sum_digits(n):
SUM = 0
while n>0:
n, mod = divmod(n, 10)
SUM += mod
return SUM
out = [sum_digits(n) for n in numsum]
output: [1, 5, 9, 13, 6]
recursive approach:
if the number must be reduced until it is a single digit (76 -> 13 -> 4), you can transform the sum_digit function into a recursive one:
def sum_digits(n):
SUM = 0
while n>0:
n, mod = divmod(n, 10)
SUM += mod
return SUM if SUM < 10 else sum_digits(SUM)
out = [sum_digits(n) for n in numsum]
output: [1, 5, 9, 4, 6]