简体   繁体   English

计算 python 中给定字符串的数字总和

[英]Compute sum of digits of a given string in python

I have this string and I want to calculate the sum, but it doesn't show the right answer, it prints 51.我有这个字符串,我想计算总和,但它没有显示正确的答案,它打印 51。

sumAndAverage = "English = 78 Science = 83 Math = 68 History = 65"

def sum_digits_string(str1):
    sum_digit = 0
    for x in str1:
        if x.isdigit():
            z = int(x)
            sum_digit = sum_digit + z

    return sum_digit 

print(sum_digits_string(sumAndAverage))

The best (Pythonic) way to do it using list comprehension and sum() .使用列表理解sum()的最佳(Pythonic)方法。 Try this:尝试这个:

sumAndAverage = "English = 78 Science = 83 Math = 68 History = 65"

li = [int(x) for x in sumAndAverage if x.isdigit()]
print("List:", li, "=", sum(li))

Output: Output:

List: [7, 8, 8, 3, 6, 8, 6, 5] = 51

If you want to calculate the sum of numbers in your string:如果要计算字符串中数字的总和:

sumAndAverage = "English = 78 Science = 83 Math = 68 History = 65"

li = [int(x) for x in sumAndAverage.split() if x.isdigit()]
print("List:", li, "=", sum(li))

Output: Output:

List: [78, 83, 68, 65] = 294

Try using re :尝试使用re

sumAndAverage = "English = 78 Science = 83 Math = 68 History = 65"
nums = re.findall('\d+', sumAndAverage)
nums = [int(num) for num in nums]
print(sum(nums))
# 294

Regex will try and find all numbers in your string, store them to a list , then you just need to sum them up.正则表达式将尝试在您的字符串中查找所有数字,将它们存储到一个list ,然后您只需将它们相加即可。

Here you have a possible solution.在这里,您有一个可能的解决方案。 Now you have as a result 229 (78 + 83 + 65).现在你得到了 229 (78 + 83 + 65)。

The problem with your code was that you were summing all the numbers in the string, but you did not consider that number may be more than one character in length.您的代码的问题是您将字符串中的所有数字相加,但您没有考虑到该数字的长度可能超过一个字符。

sumAndAverage = "English = 78 Science = 83 Math = 68 History = 65"

def sum_digits_string(str1):
    sum_digit = 0
    num = ""
    for x in str1:
        if x.isdigit():
            num += x
        else:
            if num != "":
                z = int(num)
                sum_digit += z
                num = ""
    return sum_digit 

print(sum_digits_string(sumAndAverage))

It's because you're casting each digit separately, so what you're doing is 7 + 8 + 8 + 3 + 6 + 8 + 6 + 5 which is indeed 51. What you want to do here is splitting your string and casting the entire numbers, try something like this:这是因为你分别投射每个数字,所以你正在做的是 7 + 8 + 8 + 3 + 6 + 8 + 6 + 5 这确实是 51。你想要做的是分割你的字符串并投射整个数字,尝试这样的事情:

sumAndAverage = "English = 78 Science = 83 Math = 68 History = 65"

def sum_digits_string(str1):
    sum_digit = 0

    for x in str1.split(" "):
        if x.isdigit():
            z = int(x)
            sum_digit = sum_digit + z

    return sum_digit 

print(sum_digits_string(sumAndAverage))

That is working an giving 294.这是一个给予294的工作。

str = 'English = 78 Science = 83 Math = 68 History = 65'    
a = sum([int(s) for s in str.split() if s.isdigit()])
print(a)

Your current code is printing sum of individual digits and not numbers.您当前的代码是打印单个数字的总和,而不是数字。 In your case, you can use split() method to achieve what you intend to do:在您的情况下,您可以使用split()方法来实现您打算做的事情:

sumAndAverage = "English = 78 Science = 83 Math = 68 History = 65"

def sum_digits_string(str1):
    sum_digit = 0

    for x in str1.split():
        if x.isdigit():
            sum_digit += int(x)

    return sum_digit

print(sum_digits_string(sumAndAverage))

Output: 294 Output: 294

You can also achieve this with a single line of code您也可以通过一行代码来实现这一点

sumAndAverage = "English = 78 Science = 83 Math = 68 History = 65"

Solution 1:解决方案1:

from functools import reduce

>>> reduce(lambda a, x: int(a)+int(x), [int(s) for s in sumAndAverage.split() if s.isdigit()])
294

Solution 2:解决方案2:

>>> sum([int(s) for s in sumAndAverage.split() if s.isdigit()])
294

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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