在python的List中通过其成员查找对象
问题描述
让我们假设以下简单对象:
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)...]
是否有一些内置功能可以让我获得所有年龄为 30 岁的 Mocks?当然我可以遍历他们并比较他们的年龄,但是像
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)
会很好.有这样的吗?
解决方案
您可能希望对它们进行预索引 -
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]
一张图片胜过千言万语:
a picture is worth a thousand words:
X 轴是 myList 中的 Mocks 数量,Y 轴是运行时间,以秒为单位.
X axis is number of Mocks in myList, Y axis is runtime in seconds.
- 红点是@dcrooney 的 filter() 方法
- 蓝点是@marshall.ward 的列表理解
- 隐藏在 X 轴后面的绿点是我的索引 ;-)
相关文章