簡體   English   中英

Python字符串函數中的數字總和

[英]Python Sum of digits in a string function

我的函數需要接受一個句子並返回內部數字的總和。 有什么建議嗎?

def sumOfDigits(sentence):
    sumof=0
    for x in sentence:
        if sentence.isdigit(x)== True:
            sumof+=int(x)
    return sumof

替換為:

if sentence.isdigit(x)== True:

至:

if x.isdigit():

例子:

 >>> "1".isdigit()
 True
 >>> "a".isdigit()
 False

您的代碼應類似於:

def sumOfDigits(sentence):
    sumof=0
    for x in sentence:
        if x.isdigit():
            sumof+=int(x)
    return sumof

一些Python方式:

使用列表推導:

>>> def sumof(sentence):
...     return sum(int(x) for x in sentence if x.isdigit())
... 
>>> sumof("hello123wor6ld")
12

使用過濾器,映射:

>>> def sumof(sentence):
...     return sum(map(int, filter(str.isdigit, sentence)))
... 
>>> sumof("hello123wor6ld")
12

使用正則表達式提取所有數字:

>>> import re
>>> def sumof(sentence):
...     return sum(map(int, re.findall("\d",sentence)))
... 
>>> sumof("hello123wor6ld")
12

您必須詢問x是否為數字。

def sumOfDigits(sentence):
    sumof=0
    for x in sentence:
        if x.isdigit()== True:
            sumof+=int(x)
    return sumof

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM