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

2024-04-20 04:18:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如何删除第二次出现的8,而不使用remove()删除第1次出现的8。在


Tags: remove
3条回答

remove()从列表中删除与指定值匹配的第一项。要删除第二个引用,可以使用del而不是移除。The代码应该很容易理解,我使用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)

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

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]

相关问题 更多 >