Reputation: 739
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 a test case, string, what ever that attribute type is.
Upvotes: 1
Views: 3468
Reputation: 1121406
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 for ob in larger_list if all(getattr(ob, attr) == 'some test string' for attr in list_of_attributes))
for match in 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 in vars(ob))
Upvotes: 6