作业帮 > 英语 > 作业

python:如何将一个list的第2,5,6,7,8项同时删去?

来源:学生作业帮 编辑:作业帮 分类:英语作业 时间:2024/05/10 08:38:47
python:如何将一个list的第2,5,6,7,8项同时删去?
现在一个list叫p,p=[2,5,6,7,8],如果我写成
for i in p:
del mylist[i]
就会out of range.
p.sort(reverse=True)
for i in p:
del mylist[i]
这样是删掉index是2,5,6,7,8的,如果你要第2,5,6,7,8项的话,应该是del mylist[i-1]
再问: 非常感谢,成功了。能不能讲解一下。p.sort(reverse=True)表示没有看懂
再答: it sorts p in reverse order. thus you del 8,7,6,5, then 2, avoiding disrupting the index of mylist