Reputation: 11
[1555, 1116, 221, 997]
[16, 9, 5, 25]
Upvotes: 1
Views: 788
Reputation: 62373
sum
and a list-comprehensionmap
& list
t = [1555, 1116, 221, 997]
result = [sum(int(d) for d in str(v)) for v in t]
print(result)
[16, 9, 5, 25]
for-loop
result = list()
for v in t:
r = list()
for d in str(v):
r.append(int(d))
result.append(sum(r))
%%timeit
comparisonimport numpy as np
np.random.seed(123)
t = [np.random.randint(100, 4000) for _ in range(4000000)]
%%timeit
[sum(int(d) for d in str(v)) for v in t]
5.27 s ± 60.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit
[sum(map(int, list(str(x)))) for x in t]
4.63 s ± 37 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
def sum_digits(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
%%timeit
[sum_digits(n) for n in t]
1.72 s ± 10.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Upvotes: 1
Reputation: 9484
You can use list comprehension where each number is converted to string -> splitted to list of chars -> converted to digits(numbers) back -> summed:
start = [1555, 1116, 221, 997]
end = [sum(map(int, list(str(x)))) for x in start]
print(end) # output: [16, 9, 5, 25]
Upvotes: 1
Reputation: 111
I believe what you are asking is to create an array whose elements are the sum of the digits of each number in the original array. The number digit summation is shamelessly stolen from Sum the digits of a number - python, and putting it all together you get:
def sum_digits(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
in_array = [1555, 1116, 221, 997]
out_array = [sum_digits(n) for n in in_array]
print(out_array)
Hope this helps!
Upvotes: 1