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

如何在Python中按索引替换列表元素?求函数优化方案

问题与代码优化

需求说明

  • 编写一个Python函数,包含3个输入参数:
    • randome:存储随机整数的列表;
    • indexes:包含需替换元素的非负索引的列表,需先校验索引是否在randome的有效范围内(可通过列表长度判断);
    • new_value:用于替换目标元素的新值,默认值设为True。
  • 示例效果:调用substitution_function([1, 2, 3, 4, 5], [0, 2], True)需返回列表[True, 2, True, 4, 5]。

现有待优化代码

def substitution_function(randome, indexes, new_value=True):

    result = []
    for data in indexes:
        if data <= len(source):
            result.append(new_value)
        else:
            for i in range(len(source)):
                result.append(source[i])    
    return result

代码问题分析

现有代码存在两处核心问题:

  1. 变量名错误:函数参数是randome,但代码中误用了未定义的source变量;
  2. 逻辑错误:遍历indexes来构建结果列表的逻辑完全偏离需求,无法正确生成原列表替换指定索引后的结果。

实现思路

  1. 优先创建原列表的副本,避免修改传入的原始数据;
  2. 对indexes中的每个索引做有效性校验:必须是非负整数,且小于randome的长度(列表索引从0开始,有效范围为0 <= idx < len(randome));
  3. 遍历所有有效索引,将副本中对应位置的元素替换为new_value;
  4. 返回修改后的副本。

优化后的代码

def substitution_function(randome, indexes, new_value=True):
    # 创建原列表的副本,防止修改原始数据
    result = randome.copy()
    max_valid_index = len(result) - 1
    for idx in indexes:
        # 校验索引是否为有效非负整数
        if isinstance(idx, int) and idx >= 0 and idx <= max_valid_index:
            result[idx] = new_value
    return result

测试验证

# 基础示例测试
print(substitution_function([1, 2, 3, 4, 5], [0, 2], True))  # 输出: [True, 2, True, 4, 5]

# 包含无效索引的测试
print(substitution_function([10, 20], [1, 3], "replace"))  # 输出: [10, 'replace'](索引3无效,被忽略)

# 使用默认new_value的测试
print(substitution_function([5, 6, 7], [1]))  # 输出: [5, True, 7]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:30:53