如何仅用filter、map、lambda、reduce合并相同订单号的图书订单金额
Solution Using filter, map, lambda, and reduce
Got it, let's solve this problem exactly as you asked—using only the specified tools to merge duplicate order IDs and sum their amounts. Here's a working implementation:
from functools import reduce # Your original order list order = [('5464', 39.96), ('8274', 233.82), ('9744', 404.55), ('5464', 89.91), ('9744', 404.55), ('5464', 89.91), ('88112', 274.89), ('8732', 83.93), ('7733', 208.89), ('88112', 199.75)] # Step 1: Get all unique order IDs using reduce unique_order_ids = reduce( lambda acc, item: acc if item[0] in acc else acc + [item[0]], order, [] # Initial empty list as accumulator ) # Step 2: For each unique ID, sum its amounts using filter + reduce, then map to tuples merged_orders = list(map( lambda order_id: ( order_id, reduce( lambda total, item: total + item[1], filter(lambda x: x[0] == order_id, order), 0.0 # Initial total set to 0.0 to ensure float type ) ), unique_order_ids )) print(merged_orders)
Breakdown of Each Step:
Collect Unique Order IDs:
We usereduceto iterate through the original order list. The accumulator (acc) starts as an empty list. For each item, we check if its order ID is already in the accumulator—if not, we add it. This gives us a list of all distinct order IDs (exactly 7, matching your requirement).Sum Amounts for Each Unique ID:
- For each unique ID,
filtergrabs all entries in the original list that match that ID. reducethen adds up all the amounts from those filtered entries, starting with an initial total of0.0to keep the result as a float.- Finally,
mapconverts each ID and its total into a tuple, and we convert the map object to a list to get our final result.
- For each unique ID,
When you run this code, you'll get a list of 7 tuples where each tuple contains a unique order ID and the sum of all its associated amounts.
内容的提问来源于stack exchange,提问作者Mariam Adel
相关产品推荐
相关产品推荐

