[英]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.
因此,对于我上面的列表,该值为3、6。
I know that using groupby like this: 我知道像这样使用groupby:
[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.
我知道我可以开始对每个成功的组count-1求和,以获得索引,但我认为这样做可能会更干净。
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. 只需使用
enumerate
即可与列表一起生成索引。
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. 这为每个组提供了
(start_index, value)
对。
If you really just want [3, 6]
, you can use 如果您确实只想要
[3, 6]
,则可以使用
[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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.