patternpythonMinor
Comparing values of equal-length tuple and list
Viewed 0 times
comparingequallengthandtuplevalueslist
Problem
I have a function that compares the values of a tuple and a list of equal length. It compares each value in
So for example:
What I have is below and works fine, but is there a better way to accomplish this?
combination to see if it is equal to its respective value in the path or if the value in combination is '*', that is valid.So for example:
combination=('dog', 'cat', '*'), path=['dog', 'cat', 'bird'] would return True.What I have is below and works fine, but is there a better way to accomplish this?
def _is_valid_combination(combination, path):
"""
Check if the combination is valid for the path
Keyword arguments:
combination -- tuple of pattern combination
path -- list of the actual path
"""
index = 0
for part in combination:
if (part == path[index]) or ('*' == part):
index += 1
continue
else:
return False
return TrueSolution
If I've understood your code correctly, you can do this trivially with
zip:def _is_valid_combination(combination, path):
"""
Check if the combination is valid for the path
Keyword arguments:
combination -- tuple of pattern combination
path -- list of the actual path
"""
return all(part == '*' or part == path_ for part, path_ in zip(combination, path))Code Snippets
def _is_valid_combination(combination, path):
"""
Check if the combination is valid for the path
Keyword arguments:
combination -- tuple of pattern combination
path -- list of the actual path
"""
return all(part == '*' or part == path_ for part, path_ in zip(combination, path))Context
StackExchange Code Review Q#90332, answer score: 4
Revisions (0)
No revisions yet.