Dew*_*wey 5 python search namedtuple
为了节省内存并避免冗余数据库存储(可能是预优化),我使用的是namedtuple而不是字典.
但我需要搜索recs的集合,我的字典方法是:
import operator
def query(D,key,val, keynotfound=None):
'''
D: a list of dictionaries (but I want it to be namedtuples)
key: the key to query
val: the value to search for
keynotfound: value if key is not found
Returns elements in D such that operator(D.get(key,None), val) is true
'''
op = operator.eq
def try_op(f,x,y):
try:
return f(x,y)
except Exception, exc:
return False
return (x for x in D if try_op(op, x.get(key,keynotfound),val))
Run Code Online (Sandbox Code Playgroud)
没有在namedtuple上工作任何关于如何子类化namedtuple以使其像dict一样可搜索的技巧?并非每个实例都包含与查询键相同的键/字段,因此我需要跳过该行而不是抛出键/ attr错误.
小智 9
我认为您可以使用getattr以查看该字段是否存在,如果不存在则引发异常或返回默认值.
例如,基于namedtuple文档:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
# An instance of the namedtuple
p = Point(1, 2)
In [1]: getattr(p, "x")
Out[1]: 1
In [2]: getattr(p, "z")
...
AttributeError: 'Point' object has no attribute 'z'
In [3]: getattr(f, "z", None)
Out[3]: None
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5057 次 |
| 最近记录: |