使用 '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'))
相关文章