简体   繁体   English

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

[英]How to allow a user to filter tuples in Python

I currently have a dictionary which is structured like this: 我目前有一个字典,其结构如下:

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

Within this structure, the key is a tuple representing the entry's properties. 在此结构中,键是表示条目属性的元组。 Outside of the dictionary, I have another tuple: 在字典之外,我还有另一个元组:

(property1, property2, property3)

This maps directly to the keys of the dictionary. 这直接映射到字典的键。 I would like the user to be able to input filters to get relevant keys within the dictionary, based on the property. 我希望用户能够基于属性输入过滤器以获取字典中的相关键。 Ideally, this would take the form of a dictionary as well. 理想情况下,这也应采用字典的形式。 For example, if the user entered {property1: foo} , the program would return: 例如,如果用户输入{property1: foo} ,程序将返回:

{
    (foo, bar, baz): 1
}

This is certainly possible, but my implementation was not nearly as clean as I hoped it would be. 这当然是可能的,但是我的实现并不像我希望的那样干净。 The basic approach is to construct an intermediate dictionary matcher which contains the tuple indices to be matched as keys and their corresponding strings (or what have you) as values. 基本方法是构造一个中间字典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

Some example usage is given below, it should match up with the requested usage. 下面给出了一些用法示例,它应与请求的用法匹配。

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM