如何从购物车中删除数量。 我定义了一个名为 ShoppingCart 的类来表示购物车。
class ShoppingCart:
# Initialize the shopping cart with an empty list of items
def __init__(self):
self.items = []
# Add an item with a name and quantity to the shopping cart
def add_item(self, item_name, qty):
item = (item_name, qty)
self.items.append(item)
# Remove an item with a specific name from the shopping cart
def remove_item(self, item_name):
for item in self.items:
if item[0] == item_name:
self.items.remove(item)
break
# Calculate and return the total quantity of items in the shopping cart
def calculate_total(self):
total = 0
for item in self.items:
total += item[1]
return total
我正在努力
Cart = shoppingcart()
Cart.remove_item = “orange”
但是我想保留橙色但附加橙色数量
正如其他人评论的那样,不清楚您到底要求什么。以下是从对象调用函数的一个示例:
class ShoppingCart:
# Initialize the shopping cart with an empty list of items
def __init__(self):
self.items = {}
# Add an item with a name and quantity to the shopping cart
def add_item(self, item_name, qty):
self.item = {item_name:qty}
if item_name in list(self.items.keys()):
qty_new = self.items[item_name]+qty
self.items[item_name] = qty_new
else:
self.items[item_name]=qty
# Remove an item with a specific name from the shopping cart
def remove_item(self, item_name):
self.items.pop(item_name, 'Item is not in cart!')
print(f"all items {item_name} removed from cart")
# show content of shopping cart
def show_total(self):
print("Your cart contain:")
for item_name, qty in self.items.items():
print(" ",item_name, qty)
# create the object
cart = ShoppingCart()
# add elements
cart.add_item("Orange",1)
cart.add_item("Orange",1)
# Show content
cart.show_total()
# Reduce amount
cart.add_item("Orange",-1)
cart.show_total()
# Add other items to the cart
cart.add_item("Apple",2)
cart.show_total()
# Remove item
cart.remove_item("Apple")
cart.show_total()
输出:
Your cart contain:
Orange 2
Your cart contain:
Orange 1
Your cart contain:
Orange 1
Apple 2
Your cart contain:
Orange 2
Apple 2
all items Apple removed from cart
Your cart contain:
Orange 2