[英]Cumulative sum of a numpy array and store each value into a new array
[英]How to sum the digits of each value in an array to create a new array?
[1555, 1116, 221, 997]
[16, 9, 5, 25]
您可以使用列表理解,其中每个数字都转换为字符串->拆分为字符列表->转换为数字(数字)返回->求和:
start = [1555, 1116, 221, 997]
end = [sum(map(int, list(str(x)))) for x in start]
print(end) # output: [16, 9, 5, 25]
我相信您要问的是创建一个数组,其元素是原始数组中每个数字的数字之和。 数字总和被无耻地从Sum the numbers of a number - python 中窃取,并将它们放在一起你得到:
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)
希望这可以帮助!
sum
和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
比较import 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.