【问题标题】:remove one object of a class from list of objects从对象列表中删除一个类的一个对象
【发布时间】: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


【解决方案1】:

使用 Python3 中的列表,很容易使用以下语句来实现(至少有三种可能):

  • 通过指定项目索引删除

doclist.pop(i)

  • 通过使用关键字德尔

删除文档列表[i]

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

doclist.remove(doclist[i])

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

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

【讨论】:

  • 第一种方法效果很好,非常感谢。第二种方法使用方括号时也有效
  • 在第二个中显示错误“TypeError:'list' object is not callable”,通过将其更改为 doclist.remove(doclist[i]) 它可以工作。所以请为其他人编辑它——
  • 对,我编辑了它,我打错字了,谢谢你留下我@AlbinDavis
猜你喜欢
  • 2018-07-08
  • 2020-11-07
  • 1970-01-01
  • 2016-11-14
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多