python - 从python中的一串数字中找到奇数的总和

标签 python sum

问题要求在给定一串数字的情况下求奇数之和。 因此,例如,如果给定“123”,我们应该得到 4 的总和。

这是我的尝试,它返回不正确的“4”

def sumoddnum(s):
    total= 0
    for i in range(len(s)):
        if i % 2 == 1:
            total += i
    return total 
print(sumoddnum('12345'))

我也尝试过将 s 转换为整数,但它一直给我“int is not iterable”错误

def sumoddnum(s):
    total= 0
    s= int(s)
    for i in s:
        if i % 2 == 1:
            total += i
    return total 
print(sumoddnum('12345'))

最佳答案

这应该适合你:

def sumoddnum(s):
  return sum(0 if int(i) % 2 == 0 else int(i) for i in s)

或者如果你想保持你的第一次尝试,你应该遍历你的 str 然后检查每个 int 字符的条件:

def sumoddnum(s):
    total= 0
    for i in s:
        if int(i) % 2 == 1:
            total += int(i)
    return total 
print(sumoddnum('12345'))

关于python - 从python中的一串数字中找到奇数的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59123325/

相关文章:

python - 从数组字符串中删除重复项

gridview - Yii2 : Get Sum In footer of gridview

R - 如何按年份使用累积总和并在满足条件时重新启动累积总和

python - 我应该把 models.py 放在 Django 的什么地方?

python - 如何在不运行脚本的情况下调试 Python 代码(使用 Eclipse)?

python - 在导入语句之前设置 pythonpath

python - 张量板嵌入 : "parsing metadata" hangs

mysql - 需要按非数字条件和 GROUP BY 对所有行求和

c++:哪些函数给出数组的总和?

Python Pandas : Sort and group by, 然后对第二列的两个连续行求和以获得第三列的特定值