python - TypeError:'float' 对象不可下标(第 144 行)
问题描述
这是我的代码:
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.
任何人都知道如何更正代码,这样这个错误就不会出现?
非常感谢任何帮助/反馈。谢谢!
解决方案
你看,在这部分代码:
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中下标意味着使用方括号使用元素的索引从数组中获取元素。
浮点数显然不可下标。
推荐阅读
- tensorflow - 从 Python 转换为 Tensorflow.js 后的 model.predict() 结果不同
- sql - 计数函数sql
- address-sanitizer - 发生未知地址上的 SEGV 时,如何继续执行地址清理程序?
- kubernetes - kubernetes-fabric8 watch API中的Action ADD是什么意思?
- javascript - 删除 react-dnd 中的可拖动对象
- javascript - 在javascript中将二进制数据编码为字符串
- python - 如何使用 Selenium webdriver 和 Python 抓取所有搜索结果
- tensorflow - tf.profiler 的峰值内存使用量比 nvidia-smi 多得多?
- java - bean xml中的Spring配置方法引用
- java - 使用 OpenId Connect 的多个 Liberty 服务器 SSO