如何允许用户在Python中过滤元组
我目前有一本字典,其结构如下:如何允许用户在Python中过滤元组,python,dictionary,Python,Dictionary,我目前有一本字典,其结构如下: { (foo, bar, baz): 1, (baz, bat, foobar): 5 } 在这个结构中,键是一个表示条目属性的元组。在字典之外,我还有另一个元组: (property1, property2, property3) 这直接映射到字典的键。我希望用户能够根据属性输入过滤器以获取字典中的相关键。理想情况下,这也可以采用字典的形式。例如,如果用户输入{property1:foo},程序将返回: { (foo, bar, ba
{
(foo, bar, baz): 1,
(baz, bat, foobar): 5
}
在这个结构中,键是一个表示条目属性的元组。在字典之外,我还有另一个元组:
(property1, property2, property3)
这直接映射到字典的键。我希望用户能够根据属性输入过滤器以获取字典中的相关键。理想情况下,这也可以采用字典的形式。例如,如果用户输入{property1:foo}
,程序将返回:
{
(foo, bar, baz): 1
}
这当然是可能的,但我的实现并不像我希望的那样干净。基本方法是构造一个中间字典
matcher
,其中包含要作为键匹配的元组索引及其对应的字符串(或您拥有的内容)作为值
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
下面给出了一些示例用法,它应该与请求的用法相匹配
data = {
('foo', 'bar', 'baz'): 1,
('foo', 'bat', 'baz'): 2,
('baz', 'bat', 'foobar'): 3
}
filter_map1 = {
'property1': 'foo'
}
print filter_data(data, filter_map1)
# {('foo', 'bar', 'baz'): 1, ('foo', 'bat', 'baz'): 2}
filter_map2 = {
'property2': 'bat'
}
print filter_data(data, filter_map2)
# {('foo', 'bat', 'baz'): 2, ('baz', 'bat', 'foobar'): 3}
filter_map3 = {
'property2': 'bar',
'property3': 'foobar'
}
print filter_data(data, filter_map3)
# {('foo', 'bar', 'baz'): 1, ('baz', 'bat', 'foobar'): 3}
你到底坚持什么?你试过自己解决这个问题吗?如果是这样的话,您能展示一下您尝试过的代码(并描述它不正确的地方吗)?@RobertValencia在我的用例中,相同的值可能出现在元组的不同位置。例如,键
(foo,bar,foo)
和(bat,bat,bat)
都是有效的。谢谢