Here is one way to do this with a generator:
def compress(signal): prev_t, prev_val = None, None for t, val in zip(*signal): if val != prev_val: if prev_t is not None: yield prev_t, prev_val yield t, val prev_t, prev_val = None, val else: prev_t, prev_val = t, val if prev_t is not None: yield prev_t, prev_val signal = [ [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1],
I think it would be more natural to transpose the signal , saving it like this:
[(0.0, 1), (0.1, 1), (0.2, 1), (0.3, 2), (0.4, 3), (0.5, 4), (0.6, 4), (0.7, 4), (0.8, 4), (0.9, 2), (1.0, 1), (1.1, 1)]
Thus, two calls to zip(*seq) would be superfluous, and all processing could be done on the fly.
Finally, if it is too slow for large input, it might be worth a look at using NumPy. Here is a diagram of one such solution:
import numpy as np signal = [ [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1], #time values [1,1,1,2,3,4,4,4,4,2,1,1] #function values ] def npcompress(signal): sig=np.array(signal) idx = np.where(sig[1][1:] != sig[1][:-1])[0] idx_arr = np.sort(np.array(list(set(idx) | set(idx + 1) | set([0]) | set([len(sig[1]) - 1])))) return sig.T[idx_arr] print npcompress(signal).T