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
相关产品推荐
相关产品推荐

