Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object by its member inside a List in python

Tags:

lets assume the following simple Object:

class Mock:     def __init__(self, name, age):         self.name = name         self.age = age 

then I have a list with some Objects like this:

myList = [Mock("Dan", 34), Mock("Jack", 30), Mock("Oli", 23)...] 

Is there some built-in feature where I can get all Mocks with an age of ie 30? Of course I can iterate myself over them and compare their ages, but something like

find(myList, age=30) 

would be nice. Is there something like that?

like image 266
Rafael T Avatar asked Jun 01 '12 23:06

Rafael T


People also ask

How do you search for a specific object in a list Python?

To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.

How do you check if an item is in a list Python?

We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.

How do I find an object in Python?

Get and check the type of an object in Python: type(), isinstance() In Python, you can get, print, and check the type of an object (variable and literal) with the built-in functions type() and isinstance() .


Video Answer


1 Answers

You might want to pre-index them -

from collections import defaultdict  class Mock(object):     age_index = defaultdict(list)      def __init__(self, name, age):         self.name = name         self.age = age         Mock.age_index[age].append(self)      @classmethod     def find_by_age(cls, age):         return Mock.age_index[age] 

Edit: a picture is worth a thousand words:

enter image description here

X axis is number of Mocks in myList, Y axis is runtime in seconds.

  • red dots are @dcrooney's filter() method
  • blue dots are @marshall.ward's list comprehension
  • green dots hiding behind the X axis are my index ;-)
like image 144
Hugh Bothwell Avatar answered Sep 17 '22 20:09

Hugh Bothwell