Get index from a list where the key changes, groupby
I have a list that looks like this:
myList = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3]
What I want to do is record the index where the items in the list changes value. So for my list above it would be 3, 6.
I know that using groupby like this:
[len(list(group)) for key, group in groupby(myList)]
will result in:
[4, 3, 3]
but what I want is the index where a group starts/ends rather than just then number of it开发者_JS百科ems in the groups. I know I could start summing each sucessive group count-1 to get the index but thought there may be a cleaner way of doing so.
Thoughts appreciated.
Just use enumerate
to generate indexes along with the list.
from operator import itemgetter
from itertools import groupby
myList = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3]
[next(group) for key, group in groupby(enumerate(myList), key=itemgetter(1))]
# [(0, 1), (4, 2), (7, 3)]
This gives pairs of (start_index, value)
for each group.
If you really just want [3, 6]
, you can use
[tuple(group)[-1][0] for key, group in
groupby(enumerate(myList), key=itemgetter(1))][:-1]
or
indexes = (next(group)[0] - 1 for key, group in
groupby(enumerate(myList), key=itemgetter(1)))
next(indexes)
indexes = list(indexes)
[i for i in range(len(myList)-1) if myList[i] != myList[i+1]]
In Python 2, replace range
with xrange
.
>>> x0 = myList[0]
... for i, x in enumerate(myList):
... if x != x0:
... print i - 1
... x0 = x
3
6
精彩评论