Verifique se a Lista de objetos contém um objeto com um certo valor de atributo
Quero verificar se minha lista de objetos contém um objeto com um determinado valor de atribut
class Test:
def __init__(self, name):
self.name = name
# in main()
l = []
l.append(Test("t1"))
l.append(Test("t2"))
l.append(Test("t2"))
Eu quero uma maneira de verificar se a lista contém um objeto com o nome t1, por exemplo. Como pode ser feito? Eu encontreihttps: //stackoverflow.com/a/598415/29229,
[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
Eu não quero passar por toda a lista toda vez, só preciso saber se existe uma instância que corresponda. vaifirst(...)
ouany(...)
ou algo mais faz isso?