Python:用lambda/map处理列表内元组的订单金额计算问题
Fixing the
prodcut_price Method to Process All Products Hey there! Let's break down what's going wrong and fix this step by step.
The Issue with Your Original Code
Your current prodcut_price method only processes the first product in each order. That's because the lambda directly references x[1]—the second element of each order sublist—ignoring all other product tuples that come after the store ID in each order.
The Solution
We need to adjust the method to:
- Extract every product from all orders (ignoring the store ID in each sublist).
- Calculate the cost for each individual product, applying the $10 surcharge if the subtotal is under $100.
Here's the corrected Bookshop class with the fixed method:
class Bookshop: def __init__(self): self.orders = 0 def prodcut_price(self): # Step 1: Flatten all product tuples from every order (skip store IDs) all_products = sum(map(lambda order: order[1:], self.orders), []) # Step 2: Calculate cost for each product, add surcharge if needed result = list(map( lambda prod: ( prod[0], prod[1] * prod[2] if prod[1] * prod[2] >= 100 else prod[1] * prod[2] + 10 ), all_products )) return result # Test the corrected code x = Bookshop() x.orders = [ [1, ("5464", 4, 9.99), ("8274",18,12.99), ("9744", 9, 44.95)], [2, ("5464", 9, 9.99), ("9744", 9, 44.95)], [3, ("5464", 9, 9.99), ("88112", 11, 24.99)], [4, ("8732", 7, 11.99), ("7733", 11,18.99), ("88112", 5, 39.95)] ] r1 = x.prodcut_price() print(r1)
How It Works
map(lambda order: order[1:], self.orders): For each order, this returns a list containing only the product tuples (we skip the first element which is the store ID).sum(..., []): This flattens all those separate product lists into one single list of all products across orders.- The second
mapapplies the cost logic to every product:- Compute the subtotal as
quantity × unit price - If the subtotal is $100 or more, keep it; otherwise, add $10 to cover the surcharge.
- Compute the subtotal as
Expected Output
When you run the code, you'll get a complete list of all products with their calculated costs:
[('5464', 49.96), ('8274', 233.82), ('9744', 404.55), ('5464', 99.91), ('9744', 404.55), ('5464', 99.91), ('88112', 274.89), ('8732', 93.93), ('7733', 208.89), ('88112', 199.75)]
内容的提问来源于stack exchange,提问作者Mariam Adel
相关产品推荐
相关产品推荐

