How to see if a certain class exists in a list

给你一囗甜甜゛ 提交于 2020-01-25 08:36:05

问题


I have a class, user, that has an attribute metadata.

metadata is a list of objects, each with different classes, for example:

user.metatada = [Employee(), Student(), OtherClass()]

In an update script, I need to check, if a certain type exists in a list, like so:

if type(Employee()) in user.metadata:
  replace user.metadata[indexOfThatEmployee] with new Employee()
else:
  user.metadata.append(new Employee())

is there anyway to easily to check if a certain type exists in a list?


回答1:


Got it.

test = [Employee()]

if any(isinstance(x, Employee) for x in user.metadata):
    user.metadata = [x for x in user.metadata if not isinstance(x, Employee)] + test
else:
    user.metadata = user.metadata + test

So this will check if there exists an object in the list that is an instance of the Employee class, if so, filter the list of the existing Employee object and add in the new one, if it doesn't exist, just add it in.



来源:https://stackoverflow.com/questions/50501346/how-to-see-if-a-certain-class-exists-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!