如何查看列表中是否存在某个类 [英] How to see if a certain class exists in a list

查看:183
本文介绍了如何查看列表中是否存在某个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类user,该类具有属性metadata.

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

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?

推荐答案

知道了.

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

因此,这将检查列表中是否存在作为Employee类实例的对象,如果存在,则过滤现有Employee对象的列表并添加新的对象(如果不存在),只是将其添加.

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.

这篇关于如何查看列表中是否存在某个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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