Python 字符串中数字的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14550034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum of digits in a string
提问by user1864828
if i just read my sum_digitsfunction here, it makes sense in my head but it seems to be producing wrong results. Any tip?
如果我只是sum_digits在这里阅读我的函数,它在我的脑海中是有道理的,但它似乎产生了错误的结果。任何提示?
def is_a_digit(s):
''' (str) -> bool
Precondition: len(s) == 1
Return True iff s is a string containing a single digit character (between
'0' and '9' inclusive).
>>> is_a_digit('7')
True
>>> is_a_digit('b')
False
'''
return '0' <= s and s <= '9'
def sum_digits(digit):
b = 0
for a in digit:
if is_a_digit(a) == True:
b = int(a)
b += 1
return b
For the function sum_digits, if i input sum_digits('hihello153john'), it should produce 9
对于函数sum_digits,如果我输入sum_digits('hihello153john'),它应该产生9
回答by Alex Reynolds
You're resetting the value of bon each iteration, if ais a digit.
b如果a是一个数字,您将在每次迭代中重置 的值。
Perhaps you want:
也许你想要:
b += int(a)
Instead of:
代替:
b = int(a)
b += 1
回答by óscar López
Notice that you can easily solve this problem using built-in functions. This is a more idiomatic and efficient solution:
请注意,您可以使用内置函数轻松解决此问题。这是一个更惯用和有效的解决方案:
def sum_digits(digit):
return sum(int(x) for x in digit if x.isdigit())
sum_digits('hihello153john')
=> 9
In particular, be aware that the is_a_digit()method already exists for string types, it's called isdigit().
特别要注意,该is_a_digit()方法已经存在于字符串类型中,它被称为isdigit().
And the whole loop in the sum_digits()function can be expressed more concisely using a generator expression as a parameter for the sum()built-in function, as shown above.
sum_digits()使用生成器表达式作为sum()内置函数的参数,可以更简洁地表达函数中的整个循环,如上所示。
回答by kaspersky
An equivalent for your code, using list comprehensions:
使用列表推导式与您的代码等效:
def sum_digits(your_string):
return sum(int(x) for x in your_string if '0' <= x <= '9')
It will run faster then a "for" version, and saves a lot of code.
它将比“for”版本运行得更快,并节省大量代码。
回答by shantanoo
One liner
一个班轮
sum_digits = lambda x: sum(int(y) for y in x if y.isdigit())
回答by JCash
回答by Babu
Just a variation to @oscar's answer, if we need the sum to be single digit,
只是@oscar 答案的一个变体,如果我们需要总和为个位数,
def sum_digits(digit):
s = sum(int(x) for x in str(digit) if x.isdigit())
if len(str(s)) > 1:
return sum_digits(s)
else:
return s
回答by Santosh Pillai
I would like to propose a different solution using regx that covers two scenarios:
我想提出一个使用 regx 的不同解决方案,它涵盖两种情况:
1.
Input = 'abcd45def05'
Output = 45 + 05 = 50
1.
输入 = 'abcd45def05'
输出 = 45 + 05 = 50
import re
print(sum(int(x) for x in re.findall(r'[0-9]+', my_str)))
Notice the '+' for one or more occurrences
注意一次或多次出现的“+”
2.
Input = 'abcd45def05'
Output = 4 + 5 + 0 + 5 = 14
2.
输入 = 'abcd45def05'
输出 = 4 + 5 + 0 + 5 = 14
import re
print(sum(int(x) for x in re.findall(r'[0-9]', my_str)))
回答by Leonardo Lima
Another way of doing it:
另一种方法:
def digit_sum(n):
new_n = str(n)
sum = 0
for i in new_n:
sum += int(i)
return sum

