Using #39;in#39; to match an attribute of Python objects in an array(使用 in 匹配数组中 Python 对象的属性)
问题描述
我不记得我是不是在做梦,但我似乎记得有一个函数允许类似,
I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,
foo in iter_attr(array of python objects, attribute name)
我查看了文档,但这类内容不属于任何明显列出的标题
I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers
推荐答案
使用列表推导会构建一个临时列表,如果正在搜索的序列很大,它可能会占用你所有的内存.即使序列不大,构建列表也意味着在 in
开始搜索之前遍历整个序列.
Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before in
could start its search.
使用生成器表达式可以避免临时列表:
The temporary list can be avoiding by using a generator expression:
foo = 12
foo in (obj.id for obj in bar)
现在,只要 obj.id == 12
靠近 bar
的开头,搜索就会很快,即使 bar
无限长.
Now, as long as obj.id == 12
near the start of bar
, the search will be fast, even if bar
is infinitely long.
正如@Matt 建议的那样,如果 bar
中的任何对象可能缺少 id
属性,则使用 hasattr
是个好主意:
As @Matt suggested, it's a good idea to use hasattr
if any of the objects in bar
can be missing an id
attribute:
foo = 12
foo in (obj.id for obj in bar if hasattr(obj, 'id'))
这篇关于使用 'in' 匹配数组中 Python 对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 'in' 匹配数组中 Python 对象的属性


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