如何使用remove()删除列表中第二次出现的项目而不删除Python中的第一次出现 [英] How to remove 2nd occurrence of an item in a list using remove() without removing 1st occurrence in Python

查看:33
本文介绍了如何使用remove()删除列表中第二次出现的项目而不删除Python中的第一次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何使用 remove() 在不删除第一次出现的 8 的情况下删除第二次出现的 8.

How to remove 2nd occurrence of 8 without removing 1st occurrence of 8 using remove().

推荐答案

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

It's not clear to me why this specific task requires a loop:

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)

这篇关于如何使用remove()删除列表中第二次出现的项目而不删除Python中的第一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆