元组部分匹配 [英] Tuples partial match

查看:211
本文介绍了元组部分匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于元组部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆