Candidate for a new itertool
Aahz
aahz at pythoncraft.com
Wed Mar 18 22:46:18 EDT 2009
In article <6ca71455-2fb2-4dd0-a500-2a480d815f7a at v6g2000vbb.googlegroups.com>,
Raymond Hettinger <python at rcn.com> wrote:
>
>For edge-triggered events, we need to convert a boundary-event
>predicate to groupby-style key function. The code below encapsulates
>that process in a new itertool called split_on().
>
>Would love you guys to experiment with it for a bit and confirm that
>you find it useful. Suggestions are welcome.
It seems a little esoteric for the standard library. It was non-trivial
for me to make it work with what seems to me an obvious use-case
(although perhaps I'm missing something), and I'm not sure it has enough
general utility otherwise:
from math import log10
class C:
def __init__(self, data):
self.data = data
self.index = 0
self.sentinel = None
def __iter__(self):
return self
def next(self):
if self.index >= len(self.data):
raise StopIteration
value = self.data[self.index]
self.index += 1
return value
def make_sentinel(self, value):
return (int(value / 10) + 1) * 10
def grouper(self, value):
if self.sentinel is None:
self.sentinel = self.make_sentinel(value)
return False
if value >= self.sentinel:
self.sentinel = self.make_sentinel(value)
return True
return False
if __name__ == '__main__':
for start in True, False:
L_iter = C([11, 12, 13, 20, 32])
for g in split_on(L_iter, L_iter.grouper, start):
print list(g)
print
[11, 12, 13]
[20]
[32]
[11, 12, 13, 20]
[32]
--
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
"Programming language design is not a rational science. Most reasoning
about it is at best rationalization of gut feelings, and at worst plain
wrong." --GvR, python-ideas, 2009-3-1
More information about the Python-list
mailing list