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

Python列表代码报'float' object is not subscriptable错误求助

Python代码报错排查:'float' object is not subscriptable

错误成因

报错触发的核心原因是变量类型被意外覆盖:

  • 代码开头你将listatipoIva初始化为存储每个商品IVA类型选项的列表,循环第一轮运行到条件判断分支时,你直接给listatipoIva变量本身赋值了单个数值(比如listatipoIva = listasubTotal[item] * 0.19),原本的列表被替换成了单独的浮点数/整数。
  • 当代码执行到最后一行listatotalProd.append(listatipoIva[item] + listasubTotal[item])时,你尝试用下标[item]访问浮点数,而浮点数类型不支持下标索引取值,就会抛出该错误。
  • 额外逻辑问题:你原逻辑里混淆了「用户选择的IVA类型编码」和「计算得出的IVA税额」两个不同的数据,用同一个变量存储很容易出现覆盖问题。

修正方案

  • 新增专门的列表存储每个商品计算后的IVA税额,不要覆盖存储IVA类型的原列表
  • 条件判断时用临时变量存储当前商品的IVA计算结果,不要直接给列表变量名赋值
    修正后的可运行代码如下:
acumSubTotal = 0
acumIva = 0
acumTotalProd = 0

listatotalProd=[]
listasubTotal = []
listacodProducto= []
listanomProducto=[]
listacanProducto=[]
listavalUnitario=[]
listatipoIva=[]
# 新增列表单独存储每个商品的IVA税额
listavalorIva = []
N = int(input("Digite la cantidad de Artículos a facturar: "))

for item in range(N):
    listacodProducto.append(int(input(f"Digite el código del producto {item + 1}: ")))
    listanomProducto.append((input(f"Digite el nombre del producto {item + 1}: ")))
    listacanProducto.append(float(input(f"Digite la cantidad del producto {item + 1}: ")))
    listavalUnitario.append(float(input(f"Digite el valor unitario del producto {item + 1}: ")))
    listatipoIva.append(float(input(f"Tipo de IVA (que puede ser: 1: Exento de IVA, 2: Bienes, IVA 5%, 3: General, IVA 19%) del producto {item + 1}: ")))

    subtotal_actual = listavalUnitario[item] * listacanProducto[item]
    listasubTotal.append(subtotal_actual)

    # 用临时变量存当前商品的IVA额,不要覆盖原列表
    iva_actual = 0
    if listatipoIva[item] == 1:
        iva_actual = 0
    elif listatipoIva[item] == 2:
        iva_actual = subtotal_actual * 0.05   
    else :
        iva_actual = subtotal_actual * 0.19
    listavalorIva.append(iva_actual)

    listatotalProd.append(iva_actual + subtotal_actual)

# 后续如果要算累计总额、累计IVA、累计小计直接遍历对应列表求和即可

内容的提问来源于stack exchange,提问作者Jaider Durán

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:33:46