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

如何在Kotlin中对列表分组并汇总对应数值字段?

Grouping and Summing Tuples by Month & Category

Got it, let's tackle this problem. You need to group your data by the month (first element) and category (last element) of each tuple, then sum up the three numerical values in between. Here are two straightforward ways to do this:

Using Pandas (Quick & Clean for Data Tasks)

Pandas is perfect for this kind of grouping and aggregation since it handles the heavy lifting out of the box.

import pandas as pd

# Your original data
data = [
    ("06", 80.30, 30, 20, "ProductA", "CANDY"),
    ("06", 2.5, 9, 6, "ProductB", "CANDY"),
    ("07", 8, 5.7, 1, "ProductC", "BEER"),
    ("08", 10, 2.10, 40, "ProductD", "PIZZA")
]

# Convert to DataFrame with meaningful column names
df = pd.DataFrame(data, columns=["Month", "Val1", "Val2", "Val3", "Product", "Category"])

# Group by Month and Category, then sum the numerical columns
grouped = df.groupby(["Month", "Category"])[["Val1", "Val2", "Val3"]].sum().reset_index()

# Convert back to tuples if you need that format
result = [tuple(row) for row in grouped.to_numpy()]
print(result)

This will output exactly what you're looking for:

[('06', 82.8, 39, 26, 'CANDY'), ('07', 8.0, 5.7, 1.0, 'BEER'), ('08', 10.0, 2.1, 40.0, 'PIZZA')]

Pure Python (No External Libraries)

If you can't use pandas, you can use Python's built-in itertools.groupby—just remember to sort the data first (groupby only works on consecutive matching groups).

from itertools import groupby

# Your original data
data = [
    ("06", 80.30, 30, 20, "ProductA", "CANDY"),
    ("06", 2.5, 9, 6, "ProductB", "CANDY"),
    ("07", 8, 5.7, 1, "ProductC", "BEER"),
    ("08", 10, 2.10, 40, "ProductD", "PIZZA")
]

# Sort the data by Month and Category (required for groupby)
sorted_data = sorted(data, key=lambda x: (x[0], x[-1]))

result = []
# Group by the tuple (Month, Category)
for key, group in groupby(sorted_data, key=lambda x: (x[0], x[-1])):
    month, category = key
    sum_val1 = sum_val2 = sum_val3 = 0.0
    for item in group:
        sum_val1 += item[1]
        sum_val2 += item[2]
        sum_val3 += item[3]
    # Round to match your example's decimal formatting
    result.append((month, round(sum_val1, 2) if sum_val1 % 1 != 0 else sum_val1, 
                   sum_val2, sum_val3, category))

print(result)

This will also give you the desired output:

[('06', 82.8, 39, 26, 'CANDY'), ('07', 8, 5.7, 1, 'BEER'), ('08', 10, 2.1, 40, 'PIZZA')]

Both approaches work—pick the one that fits your environment best!

内容的提问来源于stack exchange,提问作者Juan Carlos Trujillo Almanza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:12:37