简体   繁体   English

如何对数组中每个值的数字求和以创建新数组?

[英]How to sum the digits of each value in an array to create a new array?

  • Starting array: [1555, 1116, 221, 997]起始数组: [1555, 1116, 221, 997]
  • Ending array: [16, 9, 5, 25]结束数组: [16, 9, 5, 25]
  • Where each number in the ending array is the sum of the digits of the corresponding number in the starting array.其中结束数组中的每个数字是起始数组中相应数字的数字之和。
  • How do I get from the starting array to the ending array?如何从起始数组到结束数组?

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]

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:数字总和被无耻地从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)

Hope this helps!希望这可以帮助!

t = [1555, 1116, 221, 997]

result = [sum(int(d) for d in str(v)) for v in t]

print(result)
[16, 9, 5, 25]
  • Corresponding for-loop对应for-loop
result = list()
for v in t:
    r = list()
    for d in str(v):
        r.append(int(d))
    result.append(sum(r))

%%timeit comparison %%timeit比较

  • Given the following test list给定以下测试列表
import numpy as np

np.random.seed(123)
t = [np.random.randint(100, 4000) for _ in range(4000000)]
  • This answer这个答案
%%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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM