You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现字符串内数字乘以其所在位置序号后求和?

Python实现方案

1. 简洁一行实现

利用Python内置的enumerate函数可以同时获取索引和元素,直接将索引起始值设为1即可适配需求:

def calc_digit_pos_sum(num_str):
    return sum(int(digit) * pos for pos, digit in enumerate(num_str, start=1))

2. 分步实现(新手友好版)

如果需要更清晰的执行逻辑,可以拆分成多步编写:

def calc_digit_pos_sum(num_str):
    total = 0
    # 位置从1开始遍历到字符串长度
    for pos in range(1, len(num_str) + 1):
        # 取出对应位置的字符转为整数,字符串原生索引从0开始所以要减1
        digit = int(num_str[pos - 1])
        total += digit * pos
    return total

验证示例

以输入3456789为例测试:

test_input = "3456789"
print(calc_digit_pos_sum(test_input))

计算过程:3×1 + 4×2 + 5×3 + 6×4 +7×5 +8×6 +9×7 = 196,运行代码输出结果为196,符合要求。

注意事项

  • 传入参数需为纯数字字符串,包含非数字字符会抛出异常,有校验需求可以提前添加非数字判断逻辑
  • 如果输入是整数类型,先转字符串再调用即可:calc_digit_pos_sum(str(123456))

内容的提问来源于stack exchange,提问作者Brandon Chaudhary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:57:02