Quiero comprobar si mi lista de objetos contiene un objeto con un cierto valor de atributo.Compruebe si la 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 comprobar si la lista contiene un objeto con el nombre t1, por ejemplo. ¿Cómo puede hacerse esto? He encontrado https://stackoverflow.com/a/598415/292291,
[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
yo no quiero ir a través de toda la lista cada vez, sólo necesito saber si tener 1 instancia que corresponda. ¿first(...)
o any(...)
o algo más hacen eso?
La función 'first()' está disponible como un built-in llamado 'next()'. –