Skip to main content
 首页 » 编程设计

python之在元组列表中搜索部分匹配项

2025年05月04日12bonelee

如果我们有一个元组列表:

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

如何找到与搜索词部分匹配的所有项目?

例如,在上面的例子中,(_, 1)应该匹配(0, 1)和(4, 1)。

请您参考如下方法:

您可以通过使用始终与任何其他对象进行比较的特殊对象来实现通配符匹配。例如

#!/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)] 

输出

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

感谢 Antti Haapala,这里有一个更好的版本,带有更高级的 Any 类.它打印与上述代码相同的输出。

#!/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)] 

要使用第一个版本,我们确实应该创建类的一个实例,但第二个版本中的 Any 类被设计为可以直接使用。此外,第二个版本展示了如何处理 isinstance 和 subclass 检查;根据上下文,您可能希望限制这些测试。