【问题标题】:TypeError: 'float' object is not subscriptable(line 144)TypeError:'float' 对象不可下标(第 144 行)
【发布时间】:2020-06-17 03:33:59
【问题描述】:

这是我的代码:

    if opt == "4":
        while True:
            cart_for_remove()
            remove = input("Please key in the corresponding number of the item you want to remove:")
            if remove.isalpha()==True:
                print('Please enter a valid number!')
                break
            if count==0:
                print('Please add item to cart first!')
                break
            if int(remove)<=count:
                remove = int(remove) - 1
                price_remove = float(cart[remove][3].strip('$ '))
                total_price_final -= price_remove
                savings_remove = int(total_savings[remove][2].strip('$ '))
                total_savings-=savings_remove
                del cart[remove]
                print("Item has been successfully removed from cart!")
                break
            else:
                print('Please choose a valid option')
                break

在第 143 行之前一切都是正确的。在第 144 行,如果要删除项目,我尝试从总节省中删除节省,但是,出现此错误:

line 144, in <module>
    savings_remove = int(total_savings[remove][2].strip('$ '))
TypeError: 'float' object is not subscriptable.

有人知道如何更正代码,这样这个错误就不会出现了吗?

非常感谢任何帮助/反馈。谢谢!

【问题讨论】:

  • 发布完整的错误并提及第 144 行
  • 这是太多的代码,不能指望人们帮助你。尝试trim it down to the part that causes the problem
  • 这是导致问题的行 total_savings-=savings_remove 根据您的代码 total_savings 是一个无法从列表中减去值的列表。如果你想从列表中移除一个元素,你可以使用total_savings.remove(savings_remove)
  • 您好,我已相应更新

标签: python python-3.x list error-handling floating-point


【解决方案1】:

你看,在这部分代码:

        if int(remove)<=count:
            remove = int(remove) - 1
            price_remove = float(cart[remove][3].strip('$ '))
            total_price_final -= price_remove
            savings_remove = int(total_savings[remove][2].strip('$ '))
            total_savings-=savings_remove
            del cart[remove]
            print("Item has been successfully removed from cart!")
            break

total_savings[remove] 是一个浮点数。在python中下标意味着使用方括号从数组中获取元素,使用元素的索引。

浮点数显然不可下标。

【讨论】:

    猜你喜欢
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多