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 对象的属性
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
