gpt4 book ai didi

python - 在 Python 中实现对字符串中包含的整数求和的函数

转载 作者:行者123 更新时间:2023-11-30 23:11:02 24 4
gpt4 key购买 nike

因此,在读完 LPTHW 的大部分内容后,我最近拿起了 John Guttag 的《使用 Python 进行计算和编程简介》,这是修订版和扩展版。我正在将这本书与 MIT OCW 006 结合使用。现在,我试图完成书中列出的手指练习之一,特别是第 85 页第 7 章中的一个,其中作者要求您使用try- except block :

def sumDigits(s):
"""Assumes s is a string
Returns the sum of the decimal digits in s
For example, if is is'a2b3c' it returns 5"""

这是我的代码:

def sumDigits(s):
try:
total = 0
list1 = [s]
new_list = [x for x in list1 if x.isdigit()]
for e in new_list:
total += new_list[e]
return total
except TypeError:
print "What you entered is not a string."

当我使用测试输入在 IDLE 中运行此程序时,总计算结果始终为零,表明 new_list 中没有任何元素被传递到累加器。有人可以建议这是为什么吗?谢谢。

最佳答案

拉斐尔似乎已经指出了这些错误,但仍然需要注意的是,更Pythonic的方法来解决这个问题是:

return sum([int(x) for x in s if x.isdigit()]) 

关于python - 在 Python 中实现对字符串中包含的整数求和的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30385948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com