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

如何在Python中按任意分组组合对嵌套列表的元素求和

Solution for Grouped Sum of Nested Lists in Python

First, let's tackle your specific example, then generalize to a reusable method that works for any grouping rules.

Step 1: Your Specific Case

You have a nested list A and a grouping list p = [5,4,2] (note: the sum of p is 11, but A only has 10 elements—we'll handle this edge case in the general method). Here's how to compute both component-wise sums (sum each index across sublists in a group) and total sums (sum all elements in a group):

Code for Specific Case

A = [[0.8922063, 0.26672425], [0.34475611, 0.35976697], [0.33253499, 0.18923898], [0.66872466, 0.46248986], [0.72823733, 0.10537784], [0.40903598, 0.70639412], [0.79926596, 0.90095583], [0.67886544, 0.84573289], [0.3641813, 0.64296743], [0.07461196, 0.74290527]]
p = [5,4,2]

# Compute component-wise sums per group
start_idx = 0
component_results = []
for group_size in p:
    # Extract the current group
    current_group = A[start_idx:start_idx + group_size]
    if not current_group:
        break  # Stop if we've exhausted all elements in A
    # Calculate sum for each component (index) in the sublists
    num_components = len(current_group[0])
    component_sum = [sum(sublist[i] for sublist in current_group) for i in range(num_components)]
    component_results.append(component_sum)
    # Move to the next group's start index
    start_idx += group_size

# Compute total sum of all elements per group
start_idx = 0
total_results = []
for group_size in p:
    current_group = A[start_idx:start_idx + group_size]
    if not current_group:
        break
    total_sum = sum(num for sublist in current_group for num in sublist)
    total_results.append(total_sum)
    start_idx += group_size

print("Component-wise sums:", component_results)
print("Total sums per group:", total_results)

Output for Your Case

  • Component-wise sums:
    [[2.96645939, 1.3835979], [2.25134868, 3.09605027], [0.07461196, 0.74290527]]
    
  • Total sums per group:
    [4.35005729, 5.3474, 0.81751723]
    

Step 2: Generalized Method

To handle any nested list and grouping rule, we can break the problem into two reusable parts:

  1. Split the nested list into groups based on the given sizes.
  2. Apply a custom aggregation function (like sum) to each group.

Reusable Functions

def split_into_groups(nested_list, group_sizes):
    """Split a nested list into sublists based on the specified group sizes."""
    groups = []
    start = 0
    list_length = len(nested_list)
    for size in group_sizes:
        if start >= list_length:
            break
        # Extract the current group (handle cases where size exceeds remaining elements)
        end = min(start + size, list_length)
        groups.append(nested_list[start:end])
        start = end
    # Optional: Add remaining elements as a final group if group_sizes doesn't cover all
    # if start < list_length:
    #     groups.append(nested_list[start:])
    return groups

def component_wise_sum(group):
    """Compute the sum of each component (index) across all sublists in a group."""
    if not group:
        return []
    num_components = len(group[0])
    # Ensure all sublists have the same length (optional check)
    assert all(len(sublist) == num_components for sublist in group), "All sublists must have the same length"
    return [sum(sublist[i] for sublist in group) for i in range(num_components)]

def total_group_sum(group):
    """Compute the total sum of all elements in a group."""
    return sum(num for sublist in group for num in sublist)

How to Use the Generalized Method

# Split A into groups using p
groups = split_into_groups(A, p)

# Calculate component-wise sums
component_sums = [component_wise_sum(group) for group in groups]

# Calculate total sums per group
total_sums = [total_group_sum(group) for group in groups]

print("Generalized component sums:", component_sums)
print("Generalized total sums:", total_sums)

Key Features of This Approach

  • Flexibility: Works with any grouping list (even if sum of group sizes doesn't match the length of A).
  • Customization: You can easily add other aggregation functions (like average, max, min) by defining new functions and applying them to the groups.
  • Robustness: Includes checks for empty groups and ensures sublists in a group have consistent lengths (optional but useful for avoiding errors).

内容的提问来源于stack exchange,提问作者Gaurav Luitel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 19:02:39