为了节省内存和避免冗余的数据库存储(是的,可能会进行预先优化),我使用namedtuple而不是字典。
但是我需要搜索记录的集合,我的字典方法是:
但是我需要搜索记录的集合,我的字典方法是:
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))
无法在namedtuple上工作 如何子类化namedtuple以使其像字典一样可搜索? 并且,并非每个实例都包含与查询键/字段相同的键/字段,因此我需要跳过该行而不是抛出key/attr错误。