检查对象列表是否包含具有特定属性值的对象
问题描述:
我想检查我的对象列表是否包含具有某个特定值的对象。检查对象列表是否包含具有特定属性值的对象
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://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
我不想去通过整个列表每次,我只需要知道,如果它匹配那里有1个实例。将first(...)
或any(...)
还是别的什么呢?
'first()'函数可以作为内置的next()函数使用。 – 2012-02-21 02:07:16