簡體   English   中英

如何使用 remove() 刪除列表中第 2 次出現的項目而不刪除 Python 中的第一次出現

[英]How to remove 2nd occurrence of an item in a list using remove() without removing 1st occurrence in Python

a = [9,8,2,3,8,3,5]

如何使用 remove() 在不刪除第一次出現的 8 的情況下刪除第二次出現的 8。

我不清楚為什么這個特定任務需要循環:

array = [9, 8, 2, 3, 8, 3, 5]

def remove_2nd_occurance(array, value):

    ''' Raises ValueError if either of the two values aren't present '''

    array.pop(array.index(value, array.index(value) + 1))


remove_2nd_occurance(array, 8)

print(array)

您可以使用itertools.count和生成器來執行此操作:

from itertools import count

def get_nth_index(lst, item, n):
    c = count(1)
    return next((i for i, x in enumerate(lst) if x == item and next(c) == n), None)

a = [9,8,2,3,8,3,5]  
indx = get_nth_index(a, 8, 2)
if indx is not None:
    del a[indx]

print(a)
# [9, 8, 2, 3, 3, 5]

remove() 從列表中刪除與指定值匹配的第一項。 要刪除第二次出現,可以使用del代替remove。代碼應該很容易理解,我使用count來跟蹤item出現的次數,當count變為2時,該元素被刪除。

a = [9,8,2,3,8,3,5]
item  = 8
count = 0
for i in range(0,len(a)-1):
        if(item == a[i]):
               count =  count + 1
               if(count == 2):
                      del a[i]
                      break
print(a)

如果您需要刪除第二個和后續出現的目標項目,請執行此操作:

# deleting second and following occurrence of target item
a = [9,8,2,3,8,3,5]
b = []
target = 8 # target item
for i in a:
    if i not in b or i != target:
        b.append(i)
a=b
print(a)
# [9, 8, 2, 3, 3, 5]

如果您需要刪除任何項目的第二次和后續出現:

# deleting any second and following occurence of each item
a = [9,8,2,3,8,3,5]
b = []
for i in a:
    if i not in b:
        b.append(i)
a=b
print(a)
# [9, 8, 2, 3, 5]

現在,當您需要刪除第二次出現的目標項目時:

# deleting specific occurence of target item only (use parameters below)
a = [9,8,2,3,8,3,5,8,8,8]
b = []

# set parameters
target = 8 # target item
occurence = 2 # occurence order number to delete

for i in a:
    if i == target and occurence-1 == 0:
        occurence = occurence-1
        continue
    elif i == target and occurence-1 != 0:
        occurence = occurence-1
        b.append(i)
    else:
        b.append(i)
a=b
print(a)
# [9, 8, 2, 8, 3, 5, 8, 8, 8]

刪除第二次出現的python代碼

ls = [1, 2, 3, 2]
index = ls.index(2, 0)
lss = ls[index + 1:]
lss.remove(2)
print(ls[:index + 1]+lss)

刪除列表中的第二次出現

list1=["L",1,"L",2,"L"]

打印(列表1)

打印(list1.index(“L”,1))

list1.pop(2)

打印(列表1)

暫無
暫無

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

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