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

字符串形式嵌套数组的加权平均值计算实现问询

Solution for Nested Array Weighted Average Calculation

First, we need to tackle two core tasks: converting your string-based nested array into a usable Python nested list, then computing the weighted average exactly as your formula specifies. Let's break this down step by step.

Step 1: Convert String to Nested List

We have two reliable approaches, both using only Python's built-in tools (no third-party libraries):

Option 1: Use ast.literal_eval (Simple & Safe)

Python's ast module includes literal_eval, a secure function that parses strings into Python literals (like nested lists) without executing arbitrary code. This is the quickest and most robust method.

import ast

def str_to_nested_list(s):
    return ast.literal_eval(s)

Testing this with your example:

input_str = "[1,2,[2,3],[[1,2],3]]"
nested_list = str_to_nested_list(input_str)
# Result: [1, 2, [2, 3], [[1, 2], 3]]

Option 2: Manual Parser (If ast Is Restricted)

If you can't use the ast module, we can build a recursive parser that handles nested brackets by tracking their depth:

def str_to_nested_list_manual(s):
    s = s.strip()
    if not s.startswith('[') or not s.endswith(']'):
        raise ValueError("Input must be a valid nested array string")
    
    # Remove outer brackets
    s = s[1:-1].strip()
    if not s:
        return []
    
    result = []
    current_element = []
    bracket_depth = 0
    
    for char in s:
        if char == '[':
            bracket_depth += 1
            current_element.append(char)
        elif char == ']':
            bracket_depth -= 1
            current_element.append(char)
        elif char == ',' and bracket_depth == 0:
            # Split only at top-level commas
            elem = ''.join(current_element).strip()
            if elem.startswith('['):
                result.append(str_to_nested_list_manual(elem))
            else:
                result.append(int(elem))
            current_element = []
        else:
            current_element.append(char)
    
    # Add the final element
    if current_element:
        elem = ''.join(current_element).strip()
        if elem.startswith('['):
            result.append(str_to_nested_list_manual(elem))
        else:
            result.append(int(elem))
    return result

Step 2: Compute Weighted Average

Your original function was almost there, but it missed dividing by the length of each list to apply the level-specific weight. Here's the corrected recursive function that matches your formula perfectly:

def weighted_average(lst):
    total = 0
    for item in lst:
        if isinstance(item, list):
            total += weighted_average(item)
        else:
            total += item
    return total / len(lst)

How It Works

  • For each element in the list:
    • If it's an integer, add it directly to the total.
    • If it's a nested list, recursively calculate its weighted average and add that to the total.
  • Divide the total by the length of the current list to apply the 1/len weight for that level (this aligns with your formula's nested weights like 0.5* and 0.25*).

Full Example Usage

# Your input string
input_str = "[1,2,[2,3],[[1,2],3]]"

# Convert to nested list (pick either option)
nested_list = str_to_nested_list(input_str)
# Or: nested_list = str_to_nested_list_manual(input_str)

# Calculate the weighted average
result = weighted_average(nested_list)
print(result)  # Output: 1.9375

This gives exactly the result from your formula: 0.25*(1+2+(0.5*(2+3))+(0.5*(0.5*(1+2)+3))) = 1.9375.

内容的提问来源于stack exchange,提问作者Hector Esteban

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 09:27:28