简体   繁体   中英

Searching for a partial match in a list of tuples

If we have a list of tuples:

[(0,1),(1,2),(5,5),(4,1)]

How can I find all items which partially match a search term?

Eg, in the above example, (_, 1) should match (0, 1) and (4, 1) .

You can implement wild-card matching by using a special object that always compares as equal to any other object. Eg

#!/usr/bin/env python

class Any:
    def __eq__(self, other):
        return True

    def __repr__(self):
        return 'Any'

ANY = Any()

#Test
if 1:
    print ANY
    for v in [1,2,'a', 'b', (2,3,4), None]:
        print v, v == ANY
    print

def match(target, data):
    ''' Check that sequence data matches sequence target '''
    return len(data) == len(target) and all(u==v for u, v in zip(target, data))

data_list = [(0, 1), (1, 2), (5, 5), (4, 1)]
target = (ANY, 1)
print [v for v in data_list if match(target, v)]

output

Any
1 True
2 True
a True
b True
(2, 3, 4) True
None True

[(0, 1), (4, 1)]

Here's a better version with a fancier Any class, thanks to Antti Haapala . It prints the same output as the code above.

#!/usr/bin/env python

class AnyBase(type):
    def __eq__(self, other):
        return True

    def __repr__(self):
        return 'Any'

    @classmethod
    def __subclasscheck__(cls, other):
        return True

    @classmethod
    def __instancecheck__(cls, other):
        return True

class Any(object):
    __metaclass__ = AnyBase

    def __init__(self):
        raise NotImplementedError("How'd you instantiate Any?")


#Test
if 1:
    print Any
    for v in [1,2,'a', 'b', (2,3,4), None]:
        print v, v == Any
    print

def match(target, data):
    ''' Check that sequence data matches sequence target '''
    return len(data) == len(target) and all(u==v for u, v in zip(target, data))

data_list = [(0, 1), (1, 2), (5, 5), (4, 1)]
target = (Any, 1)
print [v for v in data_list if match(target, v)]

To use the first version we really should create an instance of the class, but the Any class in the second version is designed to be used directly. Also, the second version shows how to handle isinstance & subclass checks; depending on context you may wish to restrict those tests.

new_list = [i for i in old_list if i[1] == 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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