def edgedetector(it):
var = 0
old_i = object() # guaranteed to be different from everything else
for i in it:
if i != old_i:
var += 1
old_i = i
yield var
Having this generator function, you do the following:
Supposed you have an iterable it
having the values you are interested in, you do
import itertools
it_a, it_b = itertools.tee(it) # split it up
for items, val in itertools.izip(it_a, edgedetector(it_b)):
#do whatever you want to do with it
Alternative:
def edgedetector(it):
var = 0
old_i = object() # guaranteed to be different from everything else
for i in it:
if i != old_i:
var += 1
old_i = i
yield i, var # this is changed...
makes it easier:
for items, val in edgedetector(it):
#do whatever you want to do with it
object()
is the instantiation of an instance of the class object
. The generator function uses it to detect the inequality of the initial "old" object with the first element of the iterable.