def get_property_index(prop):
try:
if prop.startswith('property'):
# given 'property6' returns the integer 5 (0-based index)
return int(prop[8:]) - 1
else:
raise ValueError
except ValueError:
raise AttributeError('property must be of the format "property(n)"')
def filter_data(data, filter_map):
matcher = {}
for prop, val in filter_map.items():
index = get_property_index(prop)
matcher[index] = val
filtered = {}
for key, val in data.items():
# checks to see if *any* of the provided properties match
# if you want to check if *all* of the provided properties match, use "all"
if any(key[index] == matcher[index] for index in matcher):
filtered[key] = val
return filtered
这当然是可能的,但我的实现并不像我希望的那样干净。基本方法是构造一个中间字典
matcher
,其中包含要匹配的元组索引作为键,它们对应的字符串(或您拥有的内容)作为值。你知道吗下面给出了一些示例用法,它应该与请求的用法相匹配。你知道吗
相关问题 更多 >
编程相关推荐