一维列表删除指定元素

test=[1,2,3,4]
test.remove(3) ##删除元素3
test.pop(1)    ##删除索引为1的元素
print(test)

结果如下:
[1, 4]
一维列表删除指定元素一般使用这两种办法,一个是指定元素的值,一个是删除索引,也可以使用remove方法指定元素索引,比如test.remove(test[0]),可以删除索引位置为0的元素

二维列表删除指定元素

test=[[1,2,3],[4,5,6]]
print(test[0][2])      ##打印索引位置为0,2的元素
test.remove(test[0][2])##试图删除3
print(test)

使用这种方法看起来没有什么错误,但会报以下错误:
3

test.remove(test[0][2])##试图删除3
 ValueError: list.remove(x): x not in list


表示remove方法的参数并不在列表中,但是在打印索引位置是0,2的元素时又输出了3,解决的方法是:在test[0]中调用remove方法即:

test=[[1,2,3],[4,5,6]]
print(test[0][2])      ##打印索引位置为0,2的元素
test[0].remove(test[0][2])##试图删除3
print(test)

可以得到想要的结果:

3
 [[1, 2], [4, 5, 6]]