There is this similar question, but not quite what I am asking.
Let's say I have a list of ones and zeroes:
# i.e. [1, 0, 0, 0, 1, 1, 1, 1, 0, 1]
sample = np.random.randint(0, 2, (10,)).tolist()
I am trying to find the index of subsequences of the same value, sorted by their length. So here, we would have the following sublists:
[1, 1, 1, 1]
[0, 0, 0]
[1]
[0]
[1]
So their indices would be [4, 1, 0, 8, 9]
.
I can get the sorted subsequences doing this:
sorted([list(l) for n, l in itertools.groupby(sample)], key=lambda l: -len(l))
However, if I get repeated subsequences I won't be able to find the indices right away (I would have to use another loop).
I feel like there is a more straightforward and Pythonic way of doing what I'm after, just like the answer to the previous questions suggests. This is what I'm looking for.