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

Python列表重新赋值问题:elementwise_greater_than函数结果异常排查

代码问题排查与修复

核心错误原因

  • 混淆了列表的元素和索引:代码中for num in L遍历得到的num是列表存储的元素值(示例调用中依次是1、2、3、4),而非位置索引(正确索引应该是0、1、2、3)。你使用L[num]相当于把元素值作为下标访问列表,逻辑完全偏离需求。
  • 额外问题:代码直接修改了传入的原列表,不符合函数无副作用的常规设计,建议新建列表存储结果。

修复代码

写法1:普通循环实现

def elementwise_greater_than(L, thresh):
    """Return a list with the same length as L, where the value at index i is 
    True if L[i] is greater than thresh, and False otherwise.
    
    >>> elementwise_greater_than([1, 2, 3, 4], 2)
    [False, False, True, True]
    """
    res = []
    for num in L:
        res.append(num > thresh)
    return res

写法2:列表推导式实现(匹配列表推导模块考点,代码更简洁)

def elementwise_greater_than(L, thresh):
    """Return a list with the same length as L, where the value at index i is 
    True if L[i] is greater than thresh, and False otherwise.
    
    >>> elementwise_greater_than([1, 2, 3, 4], 2)
    [False, False, True, True]
    """
    return [num > thresh for num in L]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:06:07