Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

python - 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...