如何在Python中使用remove()删除列表中第二次出现的项目,而不删除第一次出现的项目

zour9fqk  于 2023-05-27  发布在  Python
关注(0)|答案(5)|浏览(109)
a = [9,8,2,3,8,3,5]

如何使用remove()删除第二次出现的8,而不删除第一次出现的8?

ymdaylpp

ymdaylpp1#

我不清楚为什么这个特定的任务需要一个循环:

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)
pxq42qpu

pxq42qpu2#

下面是一种使用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]
lvjbypge

lvjbypge3#

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)
mgdq6dx1

mgdq6dx14#

python代码删除第二次出现

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

0qx6xfy65#

如果您需要删除目标项的第二个 * 和以下 * 次出现,则使用此选项:

# 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]

相关问题