字符串中的数字总和

2022-11-02Python开发问题
3

本文介绍了字符串中的数字总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如果我只是在这里阅读我的 sum_digits 函数,这在我的脑海中是有道理的,但它似乎产生了错误的结果.有什么建议吗?

if i just read my sum_digits function here, it makes sense in my head but it seems to be producing wrong results. Any tip?

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

对于函数sum_digits,如果我输入sum_digits('hihello153john'),它应该产生9

For the function sum_digits, if i input sum_digits('hihello153john'), it should produce 9

推荐答案

请注意,您可以使用内置函数轻松解决此问题.这是一个更惯用和更有效的解决方案:

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())

print(sum_digits('hihello153john'))
=> 9

特别要注意,对于字符串类型已经存在 is_a_digit() 方法,它被称为 isdigit().

In particular, be aware that the is_a_digit() method already exists for string types, it's called isdigit().

sum_digits() 函数中的整个循环可以使用生成器表达式作为 sum() 内置函数的参数更简洁地表示,如如上所示.

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.

这篇关于字符串中的数字总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10