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 o
Solution 1:
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.
Solution 2:
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.
Solution 3:
For completeness, you could also use filter and a lambda expression:
filtered_lst1 = filter(lambda obj: obj.attrib==someValue, lst1)
Post a Comment for "Extract List Of Objects From Another Python List Based On Attribute"