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

使用filter重构列表邻接索引获取函数失败,求问题排查

问题排查与修正

原重构代码的核心问题

  1. Filter逻辑错误
    • Lambda表达式错误使用indices[index]访问元素:filter遍历的是indices中的候选索引值(如index+1、index-1),应直接判断当前遍历的数值是否合法。
    • 非法索引的判断条件误用and:一个索引不可能同时满足<0和>=len(elements),正确逻辑应为or。
  2. 变量命名冲突
    • Lambda参数使用index,与函数入参index重名,导致逻辑混淆。
  3. 元素移除方式错误
    • 试图通过remove(indices_delete)移除整个列表,而非单个元素;同时遍历列表时直接修改列表会引发遍历异常。

修正后的代码

def get_neighbour_indices(index, elements):
    """Returns the list of neighbor indices. It includes the element itself """
    # 生成所有候选索引:右邻居、左邻居、自身
    candidates = [index + 1, index - 1, index]
    # 过滤出合法索引:保留0到len(elements)-1之间的索引
    valid_indices = list(filter(lambda x: 0 <= x < len(elements), candidates))
    return valid_indices

验证示例

针对列表l = [1, 2, 3, 4, 5]:

  • 当index=0时,返回[1, 0](与原函数逻辑一致,包含右邻居和自身)
  • 当index=1时,返回[2, 0, 1](包含左右邻居和自身)
  • 当index=4时,返回[3, 4](包含左邻居和自身)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:35:25