lets assume the following simple Object:
class Mock:
def __init__(self, name, age):
self.name = name
self.age = age
then I
List comprehensions are almost always the faster way to do these things (2x as fast here), though as mentioned earlier indexing is even faster if you're concerned about speed.
~$ python -mtimeit -s"from mock import myList" "filter(lambda x: x.age==21, myList)"
1000000 loops, best of 3: 1.34 usec per loop
~$ python -mtimeit -s"from mock import myList" "[x for x in myList if x.age==21]"
1000000 loops, best of 3: 0.63 usec per loop
For file mock.py
in current directory:
class Mock:
def __init__(self, name, age):
self.name = name
self.age = age
myList = [Mock('Tom', 20), Mock('Dick', 21), Mock('Harry', 21), Mock('John', 22)]
You could try a filter():
filter(lambda x: x.age == 30, myList)
This would return a list with only those objects satisfying the lambda expression.
List comprehensions can pick these up:
new_list = [x for x in myList if x.age == 30]
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:
X axis is number of Mocks in myList, Y axis is runtime in seconds.