billbert
billbert

Reputation: 433

Extract list of objects from another Python list based on attribute

I have a Python list filled with instances of a class I defined.

I would like to create a new list with all the instances from the original list that meet a certain criterion in one of their attributes.

That is, for all the elements in list1, filled with instances of some class obj, I want all the elements for which obj.attrib == someValue.

I've done this using just a normal for loop, looping through and checking each object, but my list is extremely long and I was wondering if there was a faster/more concise way.

Thanks!

Upvotes: 1

Views: 889

Answers (3)

Tonechas
Tonechas

Reputation: 13723

For completeness, you could also use filter and a lambda expression:

filtered_lst1 = filter(lambda obj: obj.attrib==someValue, lst1)

Upvotes: 1

ALisboa
ALisboa

Reputation: 484

You can perhaps use pandas series. Read your list into a pandas series your_list. Then you can filter by using the [] syntax and the .apply method:

def check_attrib(obj, value):
    return obj.attrib==value

new_list = your_list[your_list.apply(check_attrib)]

Remember the [] syntax filters a series by the boolean values of the series inside the brackets. For example:

spam = [1, 5, 3, 7]
eggs = [True, True, False, False]

Than spam[eggs] returns:

[1, 5]

This is a vector operation and in general should be more efficient than a loop.

Upvotes: 1

Joshua R.
Joshua R.

Reputation: 111

There's definitely a more concise way to do it, with a list comprehension:

filtered_list = [obj for obj in list1 if obj.attrib==someValue]

I don't know if you can go any faster though, because in the problem as you described you'll always have to check every object in the list somehow.

Upvotes: 3

Related Questions