【问题标题】:How to see if a certain class exists in a list如何查看某个类是否存在于列表中
【发布时间】:2018-11-03 05:01:12
【问题描述】:

我有一个类user,它有一个属性metadata

metadata 是一个对象列表,每个对象都有不同的类,例如:

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

在更新脚本中,我需要检查列表中是否存在某种类型,如下所示:

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

是否可以轻松检查列表中是否存在某种类型?

【问题讨论】:

  • 您需要检查该属性中是否存在class,如果存在则替换它?
  • 基本上是的。

标签: python list types comparison comparison-operators


【解决方案1】:

知道了。

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 对象的列表并添加新对象,如果不存在,则只需加进去。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2023-02-22
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    相关资源
    最近更新 更多