Find object by its member inside a List in python(在python的List中通过其成员查找对象)
本文介绍了在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 轴后面的绿点是我的索引 ;-)
这篇关于在python的List中通过其成员查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在python的List中通过其成员查找对象


基础教程推荐
猜你喜欢
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01