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

Python TypeError:列表与整数无法执行减法运算问题求助

问题排查与解决

核心错误原因

你遇到的TypeError: unsupported operand type(s) for -: 'list' and 'int',本质是**amount被赋值成了列表,而非整数**:

  • 代码里amount = str(action).split('1:')执行后,比如输入1:50,split('1:')会返回['', '50']——这是一个包含两个元素的列表。
  • 你尝试转int但没生效,大概率是直接对整个列表执行int(amount),这必然报错,必须先提取列表里的金额字符串再转整数。

修复步骤

1. 正确提取并转换金额

把amount的赋值代码改成:

# 提取split后的第二个元素(索引1),去除空格后转成整数
amount = int(action.split('1:')[1].strip())

这样amount就变成了整数,后续的减法、乘法操作就不会触发类型错误。

2. 修复random.randint的错误用法

代码里rand.randint(failgamble.count)和rand.randint[wingamble.count]都是错误写法:

  • rand.randint(a, b)需要传入两个参数(最小值和最大值),用于生成指定范围的整数。
  • 随机选取列表元素更简单的方式是用rand.choice()。

修改后的代码:

# 失败时随机选一条提示
print(rand.choice(failgamble))

# 胜利时随机选一条提示
print(rand.choice(wingamble))

3. 修正余额计算逻辑(可选)

原代码不管输赢都执行bal = (bal - amount),不符合赌博的逻辑,正确逻辑应该是:

  • 失败:余额扣除赌注
  • 胜利:余额加上赢得的奖金(比如赢双倍则加amount*2)

修改后的输赢分支:

if (house % 2) == 0:
    bal -= amount  # 输了扣赌注
    print(rand.choice(failgamble))
else:
    bal += amount * 2  # 赢了加双倍奖金
    print(rand.choice(wingamble))

完整修复后的代码片段

import random as rand

iteration = 0
game = True
bal = 20  # global关键字在这里无意义,直接定义即可

while game:
    meridiem = 'AM' if (iteration % 2) == 0 else 'PM'

    print(f'type *1:(amount of cash)* to gamble money, type *2* to work a job, type *3* to find a job, type *3* to not do anything.\nyou currently have: ${bal}.\nTime: 12 {meridiem}')
    action = input('Action: ')
    if action.startswith('1:'):
        try:
            # 处理非法输入,比如非数字金额或格式错误
            amount = int(action.split('1:')[1].strip())
            if amount <=0 or amount > bal:
                print("Invalid amount!")
                continue
        except (IndexError, ValueError):
            print("Please enter valid format like '1:10'")
            continue
        
        failgamble = [
            f"you gave ${amount} to a stranger he ran off with your money.",
            "you won ! you won a trip to prison !",
            f"as you are giving money to the casino, you suddenly trip and lose conciousness. as you wake up you find out that the casino took your ${amount}"
        ]
        wingamble = [
            f"you won ${amount*2} in blackjack !",
            f"you won ${amount*2} but you made a $10 deal with a man before and ended up winning ${(amount*2)-10}."
        ]
        house = rand.randint(1,6)
        if (house % 2) == 0:
            bal -= amount
            print(rand.choice(failgamble))
        else:
            bal += amount * 2
            print(rand.choice(wingamble))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:33:16