简体   繁体   English

从键更改的列表中获取索引,groupby

[英]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.

相关问题 使用itertools groupby从分类列表中获取索引值 - Get index value from categorized List with itertools groupby 获取列值从上一行发生变化的行的索引 - Get index of row where column value changes from previous row 从值中获取键(值在列表中) - Get Key from a Value (Where value is in a list) 如何在itertools.groupby中获取key / group的索引? - How to get index of key/group in itertools.groupby? Python-从满足条件的嵌套列表中获取索引 - Python - get index from nested list where condition is met 从字典中获取值,其中键是另一个列表的值 - Get value from dict where key is value another list 如何在熊猫中的groupby()。mean()之后获取索引值列表? - How to get a list of index values after groupby().mean() in pandas? 有没有办法从单个列表制作字典,其中字典的键和值取自特定索引 - Is there a way to make a dictionary from a single list where the key and value for the dict are taken from a specific index 如何创建具有 2 个键的字典,其中第一个键是索引,第二个键来自列表,值来自 df 的列? - How can I create a dictionary with 2 keys where the the first key is the index, the second key is from a list and the values from columns of a df? Python:将列表转换成字典,其中key是列表元素的索引 - Python: Convert list to a dictionary, where key is the index of the element of the list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM