对列表中相同元素的索引进行分组的有效方法 [英] Efficient way to group indices of the same elements in a list
本文介绍了对列表中相同元素的索引进行分组的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我有一个看起来像这样的列表:
Let's say I have a list that looks like:
[1, 2, 2, 5, 8, 3, 3, 9, 0, 1]
现在,我想对相同元素的索引进行分组,因此结果应类似于:
Now I want to group the indices of the same elements, so the result should look like:
[[0, 9], [1, 2], [3], [4], [5, 6], [7], [8]]
如何有效地做到这一点?我尽量避免使用循环,因此任何使用numpy/pandas函数的实现都很棒.
How do I do this in an efficient way? I try to avoid using loops so any implementations using numpy/pandas functions are great.
推荐答案
使用熊猫GroupBy.apply
,这非常简单-使用数据对一系列索引进行分组.一个不错的好处是,您可以保持索引的顺序.
Using pandas GroupBy.apply
, this is pretty straightforward—use your data to group on a Series of indices. A nice bonus here is you get to keep the order of your indices.
data = [1, 2, 2, 5, 8, 3, 3, 9, 0, 1]
pd.Series(range(len(data))).groupby(data, sort=False).apply(list).tolist()
# [[0, 9], [1, 2], [3], [4], [5, 6], [7], [8]]
这篇关于对列表中相同元素的索引进行分组的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文