简体   繁体   中英

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!

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.

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.

为了完整起见,您还可以使用filterlambda表达式

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM