Tuples Partial Match
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 fu
Solution 1:
Why don't you use the built-in filter
:
>>> filter(lambda x: x[2] == '1.3', repo)
<<< (('framework', 'django', '1.3'), ('cms', 'fein', '1.3'))
...or a list comprehension:
>>> [x for x in repo if x[2] == '1.3']
<<< [('framework', 'django', '1.3'), ('cms', 'fein', '1.3')]
If you wanted to wrap it up into a function:
types = {'desc': 0, 'name': 1, 'version': 2}
defrepo_filter(type, critera, repo=repo, types=types):
return [x for x in repo if x[types[type]] == critera]
>>> repo_filter('version', '1.3')
<<< [('framework', 'django', '1.3'), ('cms', 'fein', '1.3')]
Solution 2:
You can use a closure to bind the pattern into the function:
defmatcher(pattern):
deff(repo):
returnall(p isNoneor r == p for r, p inzip(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'))
I've also provided a different expression for comparing the tuples.
Solution 3:
In[43]: [r for r in repo if all((p is None or q==p) for q,p in zip(r,pattern))]Out[43]: [('framework', 'django', '1.3'), ('cms', 'fein', '1.3')]
Solution 4:
defmy_filter(pattern, repo):
deff
pattern = (None, None, '1.3')
for idx, item inenumerate(pattern):
if item != Noneand item != repo[idx]:
returnFalsereturnTruereturnfilter(f, repo)
my_filter((None, None, '1.3'), repo)
Solution 5:
What about:
deff(repo, pattern=None):
ifnot pattern:
pattern = (None, None, '1.3')
for idx, item inenumerate(pattern):
if item and item != repo[idx]:
returnFalsereturnTrue
repo = (('framework', 'django', '1.3'), ('cms', 'fein', '1.3'), ('cms', 'django-cms', '2.2'))
[x for x in repo if f(x)]
>>>[('framework', 'django', '1.3'), ('cms', 'fein', '1.3')]
[x for x in repo if f(x, ('cms',None, None))]
>>> [('cms', 'fein', '1.3'), ('cms', 'django-cms', '2.2')]
Post a Comment for "Tuples Partial Match"