python - 我怎样才能在python中的一行数字中求和?

标签 python sum line

我在尝试计算和显示一系列数字的总和时遇到了麻烦。它应该是这样的:

32565854 总和:38

65985456 总和:48

17984956 总和:49

最佳答案

你可以把这条线变成字符串,然后:

sum(map(int, '32565854'))

一个文件:

with open('input.txt') as f:
    for line in f:
        line = line.strip()
        print line + ' ' + str(sum(map(int, line)))

关于python - 我怎样才能在python中的一行数字中求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33984262/

相关文章:

C# VS2012 stacktrace 行是错误的

Python 无需批处理即可读取 unicode stdin

python - 如何制作一个可以从任何目录 : the script file doesn’t have to be in the same directory as the . csv 文件运行的 python 脚本?

python - 按月查找每组中最早的记录

SQL(sqlite)比较由另一个重复行分组的行的总和

javascript - 从数组中随机选择一个元素,重复直到满足条件

arrays - perl一次添加多个数组

Java Swing : how to render a combobox with different line style?

python - 如何完全改变 tkinter.ttk Treeview 的背景颜色

wpf - 在不使用 anchor 的情况下通过一条线连接两个 WPF Canvas 元素?