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

Python中能否用变量切片列表?列表元素移除代码报错求助

修复列表切片的类型错误及逻辑问题

需求说明

编写代码移除列表中间索引及下一个索引的元素,生成新列表。例如输入[4, 3, 7, 10, 11, -2],目标输出为[4, 3, 11, -2](移除元素7和10)。

原代码及错误

原代码:

def odd_indices(lst):
  x = len(lst)/2
  new_lst = lst[:x] + lst[x-1:]
  return new_lst
  
print(odd_indices([4, 3, 7, 10, 11, -2]))

运行报错:

Traceback (most recent call last):
  File "script.py", line 9, in <module>
    print(odd_indices([4, 3, 7, 10, 11, -2]))
  File "script.py", line 5, in odd_indices
    new_lst = lst[:x] + lst[x-1:]
TypeError: slice indices must be integers or None or have an __index__ method

错误分析

  1. 类型错误原因:len(lst)/2使用普通除法,返回浮点数(比如列表长度为6时结果是3.0),而Python列表切片要求索引必须是整数,因此触发类型错误。
  2. 逻辑错误:原代码的切片逻辑lst[:x] + lst[x-1:]会重复保留中间元素,无法实现移除目标元素的效果。

修复方案

  1. 使用**整数除法//**替代普通除法,确保得到整数索引。
  2. 调整切片逻辑:要移除中间两个元素,需取列表前半部分到中间索引的前一位,再拼接中间索引后一位开始的后半部分。

修复后的代码:

def odd_indices(lst):
    x = len(lst) // 2  # 整数除法得到整数索引
    new_lst = lst[:x-1] + lst[x+1:]  # 移除索引x-1和x的元素
    return new_lst
  
print(odd_indices([4, 3, 7, 10, 11, -2]))  # 输出: [4, 3, 11, -2]

补充说明

如果列表长度为奇数(比如长度为5),要移除中间及下一个元素(索引2和3),该逻辑同样适用;若需针对奇数长度列表做不同处理,可额外添加判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 09:18:25