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

标签 python

因此,在读完 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/

相关文章:

Python:在当前目录及其所有父目录中搜索文件

python - 使用 Python 运行宏后如何保存 Excel 工作簿?

python - 递归二分查找算法在满足条件后不会停止执行,返回一个非类型对象

python - 访问 json 值

python - 预测模型的 swagger.json 示例 json 似乎没有返回预测

python - 在 python 3.7.2 中导入 numpy 后的 RAM 使用情况

python - 使用辅助轴线图制作分类或分组条形图

python - 为python构建MPI步骤时出现问题

python - 将一个 .py 脚本的输出传递给 GDB 中的另一个

python - Pandas 将列转换为不同的数据类型