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

153
我想检查我的对象列表是否包含具有特定属性值的对象。
class Test:
    def __init__(self, name):
        self.name = name

# in main()
l = []
l.append(Test("t1"))
l.append(Test("t2"))
l.append(Test("t2"))

我希望能够检查列表中是否包含名称为"t1"的对象。这该怎么做?我在https://dev59.com/HnRB5IYBdhLWcg3wiHll#598415找到了答案。

[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 == 30)          # the first match, if any

我不想每次都浏览整个列表;我只需要知道是否存在一种匹配情况。使用first(...)any(...)或其他方法可以实现这一目的吗?

3个回答

273

文档中可以清楚地看到,any()函数会在找到匹配项后立即短路并返回True

any(x.name == "t2" for x in l)

6

另一个内置函数next()可以用于此任务。它停止在条件第一次为True的实例处,就像any()一样。

next((True for x in l if x.name=='t2'), False)

此外,当条件为True时,next()可以返回对象本身(因此与OP中的first()函数类似)。
next((x for x in l if x.name == 't2'), None)

0
延伸这里已经给出的非常好的答案,我写了一个lambda函数:
InArray = lambda elem, arr: bool(any(elem == x for x in arr))   #   InArray: Is elem part of arr?

我们可以用以下方式使用它:
def main():
    DataType = ctypes.c_byte
    AllowedTypes = (ctypes.c_byte , ctypes.c_ubyte, 
                    ctypes.c_int32, ctypes.c_uint32, 
                    ctypes.c_float, ctypes.c_double)

    if InArray(DataType, AllowedTypes): pass

    if InArray(DataType, (ctypes.c_double, ctypes.c_float)): pass

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接