Check For Multiple Attribute Matches In An Array Of Objects
I have an array of objects (they are all the same object type) and they have multiple attributes, is there a way to return a smaller array of objects where all the attributes match
Solution 1:
Use a list comprehension with all()
; the following presumes that a list_of_attributes
has been predefined to enumerate what attributes you wanted to test:
sublist = [ob for ob in larger_list if all(getattr(ob, attr) == 'some test string' for attr in list_of_attributes)]
Alternatively, if your input list is large, and you only need to access the matching elements one by one, use a generator expression:
filtered = (ob forobin larger_list ifall(getattr(ob, attr) == 'some test string' forattrin list_of_attributes))
formatchin filtered:
# do something with match
or you can use the filter()
function:
filtered = filter(lambda ob: all(getattr(ob, attr) == 'some test string'for attr in list_of_attributes)
for match in filtered:
# do something with match
Instead of using a pre-defined list_of_attributes
, you could test all the attributes with the vars()
function; this presumes that all instance attributes need to be tested:
all(value == 'some test string'for key, value invars(ob))
Post a Comment for "Check For Multiple Attribute Matches In An Array Of Objects"