Someone asked How to do Python’s zip in C#?...
...which leads me to ask, what good is zip? In what scenarios do I need this? Is it really so foundational that I n
Here's a case where I used zip() to useful effect, in a Python class for comparing version numbers:
class Version(object):
# ... snip ...
def get_tuple(self):
return (self.major, self.minor, self.revision)
def compare(self, other):
def comp(a, b):
if a == '*' or b == '*':
return 0
elif a == b:
return 0
elif a < b:
return -1
else:
return 1
return tuple(comp(a, b) for a, b in zip(self.get_tuple(), Version(other).get_tuple()))
def is_compatible(self, other):
tup = self.compare(other)
return (tup[0] == 0 and tup[1] == 0)
def __eq__(self, other):
return all(x == 0 for x in self.compare(other))
def __ne__(self, other):
return any(x != 0 for x in self.compare(other))
def __lt__(self, other):
for x in self.compare(other):
if x < 0:
return True
elif x > 0:
return False
return False
def __gt__(self, other):
for x in self.compare(other):
if x > 0:
return True
elif x < 0:
return False
return False
I think zip(), coupled with all() and any(), makes the comparison operator implementations particularly clear and elegant. Sure, it could have been done without zip(), but then the same could be said about practically any language feature.