Compruebe si la Lista de objetos contiene un objeto con un determinado valor de atributo
Quiero comprobar si mi lista de objetos contiene un objeto con un determinado valor de atributo.
class Test:
def __init__(self, name):
self.name = name
# in main()
l = []
l.append(Test("t1"))
l.append(Test("t2"))
l.append(Test("t2"))
Quiero una forma de verificar si la lista contiene un objeto con el nombre t1, por ejemplo. ¿Cómo puede hacerse esto? Encontréhttps: //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
No quiero revisar toda la lista cada vez, solo necesito saber si hay 1 instancia que coincida. seráfirst(...)
oany(...)
o algo más hacer eso?