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

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.
紫魔天无痕 1年前 已收到1个回答 举报

hanerwache 幼苗

共回答了19个问题采纳率:89.5% 举报

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]

1年前 追问

5

紫魔天无痕 举报

非常感谢,成功了。能不能讲解一下。p.sort(reverse=True)表示没有看懂

举报 hanerwache

it sorts p in reverse order. thus you del 8,7,6,5, then 2, avoiding disrupting the index of mylist
可能相似的问题
Copyright © 2024 YULUCN.COM - 雨露学习互助 - 18 q. 0.056 s. - webmaster@yulucn.com