我想檢查prod_id的鍵值對add_product字典匹配任何的prod_id鍵值對在cart_products詞典串列。我使用了很多列印陳述句進行測驗,但無法獲得if item in [{product['prod_id']}] == [{cart_products['prod_id']}]要列印的值。完全可運行的代碼。任何幫助表示贊賞。
product_id = 4
product_name = 'Test name'
product_quantity = 2
product_price = 20
add_product = {'prod_id': product_id, 'prod_name': product_name, 'prod_price': product_price, 'prod_quantity': product_quantity}
cart_products = [{'prod_id': 4, 'prod_name': 'Sloths', 'prod_price': 10, 'prod_quantity': 1}, {'prod_id': 5, 'prod_name': 'Test new id', 'prod_price': 20, 'prod_quantity': 1}, {'prod_id': 6, 'prod_name': 'Add all IDs', 'prod_price': 10, 'prod_quantity': 1}, {'prod_id': 5, 'prod_name': 'Test new id', 'prod_price': 20, 'prod_quantity': 1}, {'prod_id': 6, 'prod_name': 'Add all IDs', 'prod_quantity': 1, 'prod_price': 10}]
in_cart = [{product['prod_id'] for product in cart_products}]
print(in_cart)
for product in cart_products:
print(f"Show product in cart: {product}")
for index, value in enumerate(product):
print(index, value)
for item in product:
if item in [{product['prod_id']}] == [{cart_products['prod_id']}]:
print(f"test test {item}")
else:
continue
cart_products = [add_product]
print(cart_products)
uj5u.com熱心網友回復:
我相信您的要求是在將產品添加到購物車之前檢查您的購物車中是否存在產品。您可以按照以下方法進行操作。
product_id = 4
product_name = 'Test name'
product_quantity = 2
product_price = 20
add_product = {'prod_id': product_id, 'prod_name': product_name, 'prod_price': product_price,
'prod_quantity': product_quantity}
cart_products = [{'prod_id': 4, 'prod_name': 'Sloths', 'prod_price': 10, 'prod_quantity': 1},
{'prod_id': 5, 'prod_name': 'Test new id', 'prod_price': 20, 'prod_quantity': 1},
{'prod_id': 6, 'prod_name': 'Add all IDs', 'prod_price': 10, 'prod_quantity': 1},
{'prod_id': 5, 'prod_name': 'Test new id', 'prod_price': 20, 'prod_quantity': 1},
{'prod_id': 6, 'prod_name': 'Add all IDs', 'prod_quantity': 1, 'prod_price': 10}]
def product_exists(product: dict, cart: list):
"""
A small method which checks if the product is already in cart!
:param product: New product to check
:param cart: Existing cart products
:return:
"""
new_prod_id = product.get("prod_id")
existing_prod = [ex_prod for ex_prod in cart if ex_prod.get("prod_id") == new_prod_id]
if existing_prod and len(existing_prod) > 0:
return True, existing_prod
return False, None
exists, products = product_exists(add_product, cart_products)
if exists:
print(f"Such a product exists as {products}")
else:
print("Adding product to cart")
cart_products.append(add_product)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/364694.html
標籤:蟒蛇-3.x
