元组部分匹配
我有一个元组的元组和一个元组。我有兴趣知道第一个元组的哪些元素与第二个元组(如果有)匹配,也考虑部分匹配。
这是一个过滤函数来演示我的意思。
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'))
过滤器在这种形式下是无用的,因为模式不能作为参数从外部提供(我想使用相同的函数来检查不同的输入)。有办法解决这个问题吗?
并且,为了更好地解决原始问题,可以采用另一种算法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为什么不使用内置的
过滤器
:...或 列表理解:
如果你想换行它变成一个函数:
Why don't you use the built-in
filter
:...or a list comprehension:
If you wanted to wrap it up into a function:
您可以使用闭包将模式绑定到函数中:
我还提供了一个不同的表达式来比较元组。
You can use a closure to bind the pattern into the function:
I've also provided a different expression for comparing the tuples.
怎么样:
What about:
你可以使用下面的表达式:
或者使用闭包,比如这样:
然后可以像这样调用:
You can use the following expression:
or use closure, such as this:
and then can be invoked like this: