[英]How to remove an index from a list with numbers?
我有這個問題,我有一個示例列表:
list = [6, 4, 5, 3, 10]
但是,我需要按索引刪除元素,並且當我嘗試刪除“ 4”時,我在索引4中彈出了該項目。
list.pop(4)
print(list)
Output:
list = [6, 4, 5, 3]
有辦法克服這個問題嗎?
`
list = [6, 4, 5, 3, 10]
del list[4]
print(list)
Output:
list = [6, 4, 5, 3]
`
如果知道列表中存儲的值的索引。 Python提供了一種使用pop
方法刪除該方法的好方法。
list.pop(indexWhichYouWantToDelete)
檢查此qna以獲得更多說明。
謝謝
您可以使用list.index(4)
獲得要彈出的元素的索引並使用它。
list.pop(list.index(4))
一個元素可以存在多個。 因此,解決方案是:
lis = [2,3,4,1,3,5,3]
while 3 in lis:
i = lis.index(3)
lis.pop(i)
print(lis)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.