You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅用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 use reduce to 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:

    1. For each unique ID, filter grabs all entries in the original list that match that ID.
    2. reduce then adds up all the amounts from those filtered entries, starting with an initial total of 0.0 to keep the result as a float.
    3. Finally, map converts each ID and its total into a tuple, and we convert the map object to a list to get our final result.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:14:17