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

如何修改maxvalue函数:异常提示与最大值索引返回并存

修改maxvalue函数实现指定逻辑

需求:修改现有maxvalue函数,当序列里有非数值类型元素触发TypeError时,既要打印**"仅允许输入数值类型"**的提示,又能返回序列中数值元素最大值的索引,参考已实现类似逻辑的sumvalues函数。


现有maxvalue函数

def maxvalue(values):
    """
    接收列表/数组,返回序列中最大值的索引
    """
    try:
        max_value = max(values)
    except TypeError:
        raise TypeError("仅允许输入数值类型")  # 元素非浮点数或整数时抛出异常

    indices = []
    for idx, val in enumerate(values):
        if val == max_value:
            indices.append(idx)
    return indices

参考sumvalues函数

def sumvalues(values):
    """
    接收列表/数组,返回序列中所有元素的和
    """
    total = 0.0
    for value in values:
        try:
            total += value
        except TypeError:  # 遇到非数值元素时打印提示,继续累加数值元素
            print("仅允许输入数值类型") 
    return total

修改后的maxvalue函数

def maxvalue(values):
    """
    接收列表/数组,返回数值元素最大值的索引;存在非数值元素时打印提示
    """
    has_non_numeric = False
    numeric_values = []
    
    # 遍历筛选有效数值元素,标记是否存在非数值类型
    for val in values:
        try:
            float(val)
            numeric_values.append(val)
        except (TypeError, ValueError):
            has_non_numeric = True
    
    if has_non_numeric:
        print("仅允许输入数值类型")
    
    # 空数值序列直接返回空列表
    if not numeric_values:
        return []
    
    max_value = max(numeric_values)
    # 收集原序列中等于最大值的所有索引
    indices = [idx for idx, val in enumerate(values) if val == max_value]
    
    return indices

示例调用与输出

调用代码

print(maxvalue([1,2,3,3,"e"]))

输出结果

仅允许输入数值类型

[2, 3]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:40:44