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

Python实现游戏得分计算逻辑运行结果始终为0问题排查求助

问题原因

条件判断的对象错误:map_split是拆分后得到的二维列表,结构为[['nop'], ['mul', '65'], ['sub', '20'], ['add', '75'], ['hlt']],直接判断"mul" in map_split永远返回False,所有计算分支都不会触发,得分自然始终为0。

修正方案

每次循环时取当前遍历到的单条操作指令的第一个元素作为判断依据,也可以优化循环逻辑直接遍历操作项而非索引,遇到hlt终止指令时直接跳出循环减少无效运算。

修正后代码

game_map = ['nop', 'mul 65', 'sub 20', 'add 75', 'hlt']
map_split = [item.split() for item in game_map]
print(map_split)
score = 0

for op_item in map_split:
    op = op_item[0]
    if op == 'hlt':
        break
    if op == "mul":
        score *= int(op_item[1])
    elif op == "sub":
        score -= int(op_item[1])
    elif op == "add":
        score += int(op_item[1])

print(score)

运行后最终输出得分为55,符合规则计算结果:初始得分0 → nop无操作 → 0*65=0 → 0-20=-20 → -20+75=55。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:24:04