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

如何获取Python中randint循环生成的随机数的总和

解决方案

提供两种实现思路,你可以根据自己的需求选择:

1 循环生成时直接累加(推荐)

不需要额外解析输出内容,在生成随机数时直接累加即可,修改后的代码如下:

import random
rolls = 10 # 替换为你实际设置的掷骰子次数
total = 0
for i in range(1, rolls + 1):
    # 先获取数值类型的随机数,后续再按需转成字符串打印
    current_num = random.randint(1, 6)
    total += current_num
    # 原有打印逻辑保持不变
    print(f'Roll {i}:[{current_num}]')
print(f'随机数总和:{total}')

2 从已有的输出内容中提取计算

如果已经生成了输出日志,需要从文本里提取方括号内的数字求和,可以用正则匹配实现:

import re

# 示例输出文本,如果是读取本地文件可以用open()方法加载内容
output_content = """
Roll 1:[2]
Roll 2:[5]
Roll 3:[1]
Roll 4:[1]
Roll 5:[2]
Roll 6:[4]
Roll 7:[2]
Roll 8:[5]
Roll 9:[1]
Roll 10:[6]
"""

# 正则匹配所有方括号内的数字
num_list = re.findall(r'\[(\d+)\]', output_content)
# 转为整数后求和
total = sum(map(int, num_list))
print(f'提取到的数字总和:{total}')

上述正则规则\[(\d+)\]会匹配所有被方括号包裹的数字串,捕获后转为整数即可累加得到总和。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:39:00