元组部分匹配部分

2023-09-11 06:19:08 作者:七街九友

我有元组和元组的元组。我很想知道其中第一个元组的元素相匹配的第二元组(如果有的话),考虑到部分匹配了。

I have a tuple of tuples and a tuple. I'm interested to know which elements of the first tuple match the second tuple (if any), considering partial matches too.

这是一个过滤功能来证明我是什么意思。

This is a filter function to demonstrate what I mean.

def f(repo):
    pattern = (None, None, '1.3')
    for idx, item in enumerate(pattern):
        if item != None and item != repo[idx]:
            return False
    return True

>>> repo = (('framework', 'django', '1.3'), ('cms', 'fein', '1.3'), ('cms', 'django-cms', '2.2'))
>>> filter(f, repo)
(('framework', 'django', '1.3'), ('cms', 'fein', '1.3'))

该过滤器是这种形式无用的,因为该模式不能由外部提供作为一个参数(我想用相同的函数来检查不同的输入)。有没有办法来解决这个问题?

The filter is useless in this form because the pattern can't be provided externally as an argument (I want to use the same function to check different inputs). Is there a way to fix this?

和,这可能是另一种算法接受一个更好的办法,原来的问题?

And, what could be another algorithm to embrace for a better approach to the original problem?

推荐答案

您可以使用一个封闭的模式绑定到函数:

You can use a closure to bind the pattern into the function:

def matcher(pattern):
    def f(repo):
        return all(p is None or r == p for r, p in zip(repo, pattern))
    return f

>>> repo = (('framework', 'django', '1.3'), ('cms', 'fein', '1.3'), ('cms', 'django-cms', '2.2'))
>>> pattern = (None, None, '1.3')
>>> filter(matcher(pattern), repo)
(('framework', 'django', '1.3'), ('cms', 'fein', '1.3'))

我还提供了不同的EX pression用于比较的元组。

I've also provided a different expression for comparing the tuples.