簡體   English   中英

如何刪除不是列表中的第一次出現?

[英]How can I remove not a first occurrence in the list?

所以我有幾個看起來像這樣的列表: lst = [1, 3, 1, 1] 和 lst2 = [3]

我需要從 lst 中刪除“1”,但是一個特定的“1”:lst[2] 我需要將 lst2 中的“3”插入到那個特定的位置。

刪除並沒有真正的幫助,因為它刪除了第一次出現。

非常感謝!

您可以使用 del 刪除python中給定索引處的元素。 要在特定位置插入元素,可以使用 in insert(index, element)。 在您的情況下,以下將起作用:

lst = [1, 3, 1, 1]
lst2 = [3]
del lst[2] #This will delete element at position 2 from lst list
lst.insert(2,3) #This will insert element 3 at position 2 in lst
lst=[int(input("Enter a number into the list: "))]
lstcopy=lst
while True:
    new=input("Enter one more number into the list: ")
    if not new:
        break
    lst.append(int(new))
findMe=int(input("Enter the number to find: "))
findMeOccurence=int(input("Enter the occurence number of "+str(findMe)+" that you want to find: "))
idx=-1
error=False
try:
    for i in range(findMeOccurence):
        idx+=1
        lstcopy=lstcopy[idx:]
        idx=lstcopy.index(findMe)
except:
    print("Your number does not exist at that occurence.")
    error=True
if not error:
    del lst[idx+1]
    print("\nThis is your list with "+str(findMe)+" removed at occurence "+str(findMeOccurence)+":\n"+str(lst))

這樣做是獲取您的列表(您可以預設它並刪除列表獲取代碼),在lstcopy復制它,獲取要查找的編號(您可以再次預設)以及找到它的位置(可以預設)這里也)。 然后它將idx設置為-1並將errorFalse try ,完成了一個循環:

  1. idx增加 1
  2. 削減lstcopy以便下一步不會遞歸地執行此操作
  3. 使用index獲取新的idx

index當它找不到給定的項目時會引發異常,並且會被except捕獲,表示您的號碼不存在(因為循環尚未完成,因此未找到該事件)。 然后它將error設置為True

在結尾部分,它檢查error是否為False (因為默認情況下它是False ,我們使用的是not關鍵字),如果是,則表示錯誤消息(“您的號碼在該次出現時不存在。”)尚未給出,因此使用del lst[idx+1]刪除索引並向用戶顯示新列表。 這就是制作lstcopy的原因:因為最后,它需要完整的lstdel ,而不是從那個循環中切出的lstcopy

我已經在 Python 3.8.1 上試過了,你自己試試,然后在評論中告訴我它是否有效!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM