如何允许用户在Python中过滤元组

2024-10-01 02:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有一本字典,结构如下:

{
    (foo, bar, baz): 1,
    (baz, bat, foobar): 5
}

在这个结构中,键是表示条目属性的元组。在字典之外,我还有一个元组:

(property1, property2, property3)

这直接映射到字典的键。我希望用户能够输入过滤器,以获得字典内的相关键,基于属性。理想情况下,这也可以采用字典的形式。例如,如果用户输入{property1: foo},程序将返回:

{
    (foo, bar, baz): 1
}

Tags: 用户过滤器字典属性foobar条目baz
1条回答
网友
1楼 · 发布于 2024-10-01 02:31:45

这当然是可能的,但我的实现并不像我希望的那样干净。基本方法是构造一个中间字典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}

相关问题 更多 >