[英]Sum digits of numbers in a list
Trying to write a function that takes a list like:尝试编写一个接受如下列表的函数:
x = [1, 13, 14, 9, 8]
for example and sums the digits like:例如,对数字求和,如:
1 + (1+3) + (1+4) + 9 + 8 = 27
What I have attempted thus far:到目前为止我尝试过的:
def sum_d(x):
if not x:
return 0
else:
return x[0] + sum_d(x[1:])
How about this beauty:这个美女怎么样:
the_sum = sum(int(char) for n in x for char in str(n))
print(the_sum) # prints -> 27
What is happening here is that i am going through all elements of the list one by one ( for n in x
), i convert them to strings to be able to iterate through each character by character ( for char in str(n)
) and finally sum all the generated numbers after converting them back to integers ( int(char)
)这里发生的事情是,我正在逐个遍历列表中的所有元素( for n in x
),我将它们转换为字符串以便能够逐个字符地遍历每个字符( for char in str(n)
)和最后将所有生成的数字转换回整数后求和( int(char)
)
You can easily convert the above into a function like so:您可以轻松地将上述内容转换为如下函数:
def sum_of_characters(my_list):
return sum(int(char) for n in my_list for char in str(n))
As @Jim noticed, the proposed solution here cannot handle negative numbers in the list.正如@Jim 所注意到的,这里提出的解决方案无法处理列表中的负数。 Modifying it so that it doesn't throw an error can be done by checking to make sure char
is a digit and not a sign:可以通过检查以确保char
是数字而不是符号来修改它以使其不会引发错误:
def sum_of_characters(my_list):
return sum(int(char) for n in my_list for char in str(n) if char.isdigit())
Making it work though while at the same time keeping it as a single generator expression is quite a task..让它工作同时保持它作为单个生成器表达式是一项艰巨的任务..
Just for the record, an other variant that just uses a generator expression and can handle negative numbers that are either < 10 or would break up like so: -14 -> -1 + 4 is this:只是为了记录,另一个变体只使用生成器表达式并且可以处理小于 10 或会像这样分解的负数:-14 -> -1 + 4 是这样的:
def sum_of_characters(my_list):
return eval('+'.join(str(char) for n in x for char in str(n)))
A slight modification, and your original code will work :稍作修改,您的原始代码将起作用:
def sum_d(x):
x = str(x)
if len(x) == 1:
return int(x)
else:
return int(x[0]) + sum_d(int(x[1:]))
also possible in single line :也可以单行:
sum(int(y) for y in (chain(*[str(x) for x in [1, 13, 14, 9, 8]])))
Explained here :在这里解释:
>>> from itertools import chain
>>> [str(x) for x in [1, 13, 14, 9, 8]]
['1', '13', '14', '9', '8']
>>> chain(*[str(x) for x in [1, 13, 14, 9, 8]])
<itertools.chain object at 0x7feadcd067d0>
>>> list(chain(*[str(x) for x in [1, 13, 14, 9, 8]]))
['1', '1', '3', '1', '4', '9', '8']
>>> sum(int(y) for y in (chain(*[str(x) for x in [1, 13, 14, 9, 8]])))
27
x = [1,13,14,9,8]
number = 0
for element in x:
my_string = str(element)
for i in range(len(my_string)):
number += int(my_string[i])
print(number)
This will do it, there might be a way to slice ints that doesn't involve converting them to strings though.这将做到这一点,但可能有一种方法可以对 int 进行切片,但不涉及将它们转换为字符串。
def sumx(x):
for i in range(0,len(x)):
if(x[i]>10):
sum=0
while(x[i]>0):
sum+=x[i]%10
x[i]=x[i]/10
x[i]=sum
print(x)
>>> sumx(x)
[5, 4, 5, 9, 8]
def SumofNumDig(l):
x = []
for i in l:
c = 0
for j in str(i):
c += int(j)
x.append(c)
return x
n = int(input("Enter the no of elements in the list: "))
l = []
l = list(map(int, input("enter the list of elements:").strip().split(' ')))[:n] #to get integer input
print(SumofNumDig(l))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.