我有一个列表,看起来像这样:
myList = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3]我想要做的是记录列表中项的变更值的索引。因此,对于我上面的列表,它将是3,6。
我知道像这样使用groupby:
[len(list(group)) for key, group in groupby(myList)]将导致:
[4, 3, 3]但我想要的是一个组的开始/结束位置的索引,而不仅仅是组中的项目数。我知道我可以开始对每个成功的组计数求和-1来获得索引,但我认为可能有一种更简洁的方法。
感激不尽。
发布于 2011-10-01 04:38:17
只需使用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)]这将为每个组提供成对的(start_index, value)。
如果你真的只想要[3, 6],你可以使用
[tuple(group)[-1][0] for key, group in
groupby(enumerate(myList), key=itemgetter(1))][:-1]或
indexes = (next(group)[0] - 1 for key, group in
groupby(enumerate(myList), key=itemgetter(1)))
next(indexes)
indexes = list(indexes)发布于 2011-10-01 04:37:18
[i for i in range(len(myList)-1) if myList[i] != myList[i+1]]在Python2中,用xrange替换range。
发布于 2011-10-01 04:49:20
>>> x0 = myList[0]
... for i, x in enumerate(myList):
... if x != x0:
... print i - 1
... x0 = x
3
6https://stackoverflow.com/questions/7615758
复制相似问题