我是python的新手,如果用户输入的值在该列表的对象中,我将无法从列表中删除元素。所以我正在尝试构建一个购物车,并且有一个名为remove_item()的方法。它将接受您要作为字符串删除的项目的名称。然后循环遍历itemToPurchase类的对象以检查它的属性。如果我们找到它,我们从列表中删除整个对象,如果不继续loping,如果我们没有在整个循环中找到它通过一个除外并继续
cart_item = []
def remove_item(self, remove):
try:
for item in cart_item:
#print(item.item_name)
if(item.item_name == remove):
cart_item.remove(item)
print('item removed')
else:
raise ValueError('Item not found in cart. Nothing removed.')
except ValueError as excpt:
print(excpt)
答案 0 :(得分:-1)
您的代码修改很少
试试这个: -
def remove_item(ramove):
cart_item = ["apple","orange"]
try:
for item in cart_item:
if ramove in item:
cart_item.remove(item)
return cart_item
else:
raise ValueError('Item not found in cart. Nothing removed.')
except ValueError as excpt:
print(excpt)