【发布时间】:2021-07-11 18:51:18
【问题描述】:
我需要根据条件从对象列表中删除一个对象。 在 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,docname,deptname)
id=int(input())
res=Hospital.selectDoctor(id,doclist)
print(res)
【问题讨论】:
-
在Python中使用list,很容易实现:doclist.pop(i)
-
删除项目时不能像这样迭代列表。这将导致未选中的项目并引发
IndexError(如果有任何删除)。
标签: python-3.x list class listobject