If you wanted to group runs of adjacent values instead, that should be easy, right?
Let's give a concrete example:
>>> runs([0, 1, 2, 3, 5, 6, 7, 10, 11, 13, 16]) [(0, 3), (5, 7), (10, 11), (13, 13), (16, 16)]If we could make groupby give us (0, 1, 2, 3), then (5, 6, 7), etc.—this would be trivial.
Unfortunately, that's easier said than done.
What's the key?
To customize groupby, you give it the same kind of key function as all of the sorting-related functions: a function that takes each value and produces a key that can be compared to another value's key. So, if you want to group 1 and 2 into the same run… what key does that?It may not be immediately obvious how to build such a key. But the functools module comes with a helper called cmp_to_key that does that automatically. You give it an "old-style comparison function"—that is, a function on two arguments that returns -1, 0, or 1 depending on whether the left argument is less than, equal to, or greater than the right—and gives you a key function. And that comparison function is obvious.
But if you try it, this doesn't actually work:
>>> def adjacent_cmp(x, y): ... if x+1 < y: return -1 ... elif x > y: return 1 ... else: return 0 >>> adjacent_key = functools.cmp_to_key(adjacent_cmp) >>> a = [0, 1, 2, 3, 5, 6, 7, 10, 11, 13, 16] >>> [list(g) for k, g in itertools.groupby(a, adjacent_key)] [[0, 1], [2, 3], [5, 6], [7], [10, 11], [13], [16]]It groups 0 and 1 together, but 2 isn't part of the group. Why?
Because groupby is remembering the first key in the group, and testing each new value against it, not remembering the most recent key in the group. Since the whole point of the key function is that the first key and the most recent key are equal, it's perfectly within its rights to do this—and, since it makes the code a little simpler and a little more efficient, it makes sense that it would.
There are two ways to fix this: We could change groupby (after all, the documentation comes with a pure Python equivalent) to remember the most recent key in the group instead of the first one, or we could create a stateful key callable that caches the last value that compared equal instead of its initial value. The second one seems hackier and harder, so let's start with the first.
Customizing groupby
First, let's just take the code out of the docs and run it:>>> [list(g) for k, g in itertools.groupby(a, adjacent_key)] TypeError: other argument must be K instanceIt's not actually equivalent after all! What's the difference?
The Python implementation has lines like this:
while self.currkey == self.tgtkey:That seems reasonable, but these values start off as an object() sentinel, and the key returned by a key function created by cmp_to_key doesn't know how to compare itself to anything but another key returned by such a function. It's K.__eq__ will raise a TypeError, and the == operator fallback code will take this to mean that means a K instance can only be compared to another K instance and generate the different TypeError we're ultimately seeing.
So, the first fix we have to make is to change this comparison, and a similar one a few lines down, to deal with the sentinel explicitly (which also means we have to store the sentinel so we can compare to it). I won't show the code for this or the next change, because you don't really need to see the broken code; the last version will have all of the changes.
So let's try it again:
>>> [list(g) for k, g in groupby(a, functools.cmp_to_key(adjacent_cmp))] [[0], [1], [2], [3], [5], [6], [7], [10], [11], [13], [16]]It's still not equivalent. What's different now?
If you look at the comparisons, they look like this:
while self.currkey == self.tgtkey:That's clearly backward. Obviously when you're doing an ==, it shouldn't matter which value is on which side… except that we've deliberately distorted the meaning of == so that being 1 less counts as the same, without almost making 1 more count as the same. We could, and probably should, change our cmp function to do this... but if we're already changing the "equivalent" pure Python groupby to actually be equivalent, we might as well change this too.
So, with that change, let's try again:
>>> [list(g) for k, g in itertools.groupby(a, adjacent_key)] [[0, 1], [2, 3], [5, 6], [7], [10, 11], [13], [16]]OK, now we're back to where we wanted to be. The change we wanted was to just remember the last key in the group instead of the first. Which means we need to change this line to remember the last key:
self.currkey = self.keyfunc(self.currvalue)And let's try it out:
>>> [list(g) for k, g in groupby(a, functools.cmp_to_key(adjacent_cmp))] [[0, 1, 2, 3], [5, 6, 7], [10, 11], [13], [16]]But wait, there's another problem. If the last key is part of a group, but doesn't compare equal to the start of that group, it gets repeated on its own. For example:
>>> a = [1, 2, 3] >>> [list(g) for k, g in groupby(a, functools.cmp_to_key(adjacent_cmp))] [[1, 2, 3], [3]]Why does this happen? Well, we're updating tgtkey within _grouper, but that doesn't affect self.tgtkey. As far as I can tell, the only reason _grouper takes tgtkey as an argument instead of using the attribute is a micro-optimization (local variable lookup is faster than attribute lookup), one that's rarely going to make any difference in your program's performance (especially considering all the other attribute lookups we're doing in the same loop). So, the easy fix is to not do that.
Putting it all together:
class groupby: # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D def __init__(self, iterable, key=None): if key is None: key = lambda x: x self.keyfunc = key self.it = iter(iterable) self.sentinel = self.tgtkey = self.currkey = self.currvalue = object() def __iter__(self): return self def __next__(self): while (self.currkey is self.sentinel or self.tgtkey is not self.sentinel and self.tgtkey == self.currkey): self.currvalue = next(self.it) # Exit on StopIteration self.currkey = self.keyfunc(self.currvalue) self.tgtkey = self.currkey return (self.currkey, self._grouper()) def _grouper(self): while self.tgtkey is self.sentinel or self.tgtkey == self.currkey: yield self.currvalue self.currvalue = next(self.it) # Exit on StopIteration self.tgtkey, self.currkey = self.currkey, self.keyfunc(self.currvalue)At any rate, this has turned into a much more complicated solution than it originally appeared. Is there a better way? Stateful keys sounded a lot worse, but let's see if they really are.
Stateful keys
So, what would a stateful key look like? Well, let's look at what our existing key looks like. cmp_to_key is actually implemented in pure Python (with an optional C accelerator), and it looks like this:def cmp_to_key(mycmp): """Convert a cmp= function into a key= function""" class K(object): __slots__ = ['obj'] def __init__(self, obj): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 __hash__ = None return KSo, we want to update self.obj = other whenever they're equal, in all six comparison functions.
But we already know from the groupby source that it never calls anything but ==. And really, we don't want this key function to work with anything that calls, say, <; the idea of "sorting by adjacency" doesn't sound as compelling (or even as coherent) as grouping by adjacency. So, let's just implement that one operator.
While we're at it, let's fix the problem mentioned above, that if you compare our keys backward you get the wrong answer. If we can make a==b and b==a always the same, that makes things even less hacky.
class AdjacentKey(object): __slots__ = ['obj'] def __init__(self, obj): self.obj = obj def __eq__(self, other): ret = self.obj - 1 <= other.obj <= self.obj + 1 if ret: self.obj = other.obj return retDoes it work?
>>> [list(g) for k, g in itertools.groupby(a, AdjacentKey)] [[0, 1, 2, 3], [5, 6, 7], [10, 11], [13], [16]]Yes, and on the first try. As it turns out, that was actually easier, not harder. Sometimes it's worth looking under the covers of the standard library.
From groups to runs
Now we can easily write the function we wanted in the first place:def first_and_last(iterable): start = end = next(iterable) for end in iterable: pass return start, end def runs(iterable): for k, g in itertools.groupby(iterable, AdjacentKey): yield first_and_last(g)
Beyond 1
We've baked the notion of adjacency into our key: within +/- 1. But you might want a larger or smaller cutoff. Or, for that matter, a different type of cutoff—e.g., timedelta(hours=24). Or you might want to apply a key function to the values before comparing them, which would make it easy to implement a "natural sorting" rule (like the Mac Finder), so "file001.jpg" and "file002.jpg" are adjacent. Or you might want a different comparison predicate all together—e.g., within +/- 1% instead of +/- 1.All of these are easy to add:
def adjacent_key(cutoff=1, key=None, predicate=None): if key is None: key = lambda v: v if predicate is None: def predicate(lhs, rhs): return lhs - cutoff <= rhs <= lhs + cutoff class K(object): __slots__ = ['obj'] def __init__(self, obj): self.obj = obj def __eq__(self, other): ret = predicate(key(self.obj), key(other.obj)) if ret: self.obj = other.obj return ret return KLet's test it out. (I'm going to from … import a bunch of things here to make it a bit more concise.)
>>> [list(g) for k, g in groupby(a, adjacent_key(2))] [[0, 1, 2, 3, 5, 6, 7], [10, 11, 13], [16]] >>> b = [date(2001, 1, 1), date(2001, 2, 28), date(2001, 3, 1), date(2001, 3, 2), date(2001, 6, 4)] >>> [list(g) for k, g in groupby(b, adjacent_key(timedelta(days=1)))] [[datetime.date(2001, 1, 1)], [datetime.date(2001, 2, 28), datetime.date(2001, 3, 1), datetime.date(2001, 3, 2)], [datetime.date(2001, 6, 4)]] >>> def extract_number(s): return int(search(r'\d+', s).group(0)) >>> c = ['file001.jpg', 'file002.jpg', 'file010.jpg'] >>> [list(g) for k, g in groupby(c, adjacent_key(key=extract_number)] [['file001.jpg', 'file002.jpg'], 'file010.jpg'] >>> d = [1, 1.01, 1.02, 10, 99, 100] >>> [list(g) for k, g in groupby(d, predicate=lambda x, y: 1/1.1 < x/y < 1.1))] [[1, 1.01, 1.02], [10], [99, 100]]And let's make runs more flexible, while we're at it:
def runs(iterable, *args, **kwargs): for k, g in itertools.groupby(iterable, adjacent_key(*args, **kwargs)): yield first_and_last(g)A quick test:
>>> list(runs(c, key=extract_number)) [('file001.jpg', 'file002.jpg'), ('file010.jpg', 'file010.jpg')]And we're done.
Add a comment