相关疑难解决方法(0)

检查对象列表是否包含具有特定属性值的对象

我想检查我的对象列表是否包含具有特定属性值的对象.

class Test:
    def __init__(self, name):
        self.name = name

# in main()
l = []
l.append(Test("t1"))
l.append(Test("t2"))
l.append(Test("t2"))
Run Code Online (Sandbox Code Playgroud)

我想要一种检查列表是否包含名称为t1的对象的方法.怎么做到呢?我找到了/sf/answers/41889081/,

[x for x in myList if x.n == 30]               # list of all matches
any(x.n == 30 for x in myList)                 # if there is any matches
[i for i,x in enumerate(myList) if x.n == 30]  # indices of all matches

def first(iterable, default=None):
    for item in iterable:
        return item
    return default

first(x for x in myList if x.n …
Run Code Online (Sandbox Code Playgroud)

python attributes list any

84
推荐指数
2
解决办法
5万
查看次数

标签 统计

any ×1

attributes ×1

list ×1

python ×1