从对象列表中删除一个类的一个对象

问题描述

我需要根据条件从对象列表中删除一个对象。 在 selectDoctor 方法中,我需要从列表中删除其 docid 等于给定 id 的对象并返回删除的列表。

class Doctor:
    def __init__(self,docid,docname,deptname):
        self.docid = docid
        self.docname = docname
        self.deptname = deptname

class Hospital:
        def selectDoctor(id,doclist):
        for i in range(0,len(doclist)):
            if doclist[i].docid==id: //in this condition I need to remove that object from list
                doclist.remove(i) //by removing like this it is showing error
        return doclist

for i in range(5):
    docid=int(input())
    docname=input()
    deptname=input()
    doclist.append(Doctor(docid,deptname)

id=int(input())
res=Hospital.selectDoctor(id,doclist)
print(res)

解决方法

Python3 中使用列表,使用以下语句很容易实现这一点(您至少有三种可能性):

  • 通过指定项目索引删除

doclist.pop(i)

  • 通过指定项目索引(也允许索引范围,例如 del doclist[0:2] 用于删除给定列表的前三个项目)使用关键字删除

del doclist[i]

  • 通过指定项目本身来删除

doclist.remove(doclist[i])

参考:https://docs.python.org/3.8/tutorial/datastructures.html

在修正错误后,请随时为答案投票...

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...