简体   繁体   中英

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 items 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.

[i for i in range(len(myList)-1) if myList[i] != myList[i+1]]

在Python 2中,将range替换为xrange

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)
>>> x0 = myList[0]
... for i, x in enumerate(myList):
...     if x != x0:
...         print i - 1
...         x0 = x
3
6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM