Listing indices in a list of lists

I'm looking for a magical Python method to pack a list of indexes of this type

[0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 4, 4]

with each index grouped in a specific list:

[[0, 1, 2, 3, 4], [5, 6, 7], [8, 9], [10], [11, 12, 13]]

I already did this with list comprehension plus the append loop as follows, but I feel there is a one-line Python that can do this. I work on lists that sometimes reach 10,000+ items, so performance is important.

li = [0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 4, 4]

result = [[] for _ in xrange(max(li)+1)]

for i in xrange(len(li)):
    result[li[i]].append(i)
+4
source share
4 answers

Not sure if this is better than the other answers, but it seemed interesting to me to figure this out:

li = [0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 4, 4]

from collections import Counter

result = []
last = 0

for k,v in sorted(Counter(li).items()):
    result.append(list(range(last, last + v)))
    last += v
+2
source

itertools.groupby . .

from itertools import groupby
def index_list(l):
    temp = 0
    index_list = []
    for key, group in groupby(l):
        items = len(list(group))
        index_list.append([i+temp for i in range(items)])
        temp += items
    return index_list

>>> l = [0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 4, 4]
>>> index_list(l)
[[0, 1, 2, 3, 4], [5, 6, 7], [8, 9], [10], [11, 12, 13]]
+3

This can be done using the following expression:

>>> li = [0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 4, 4]
>>> [[i for i, n in enumerate(li) if n == x] for x in sorted(set(li))]
[[0, 1, 2, 3, 4], [5, 6, 7], [8, 9], [10], [11, 12, 13]]
+1
source

My implementation:

li = [0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 4, 4]
lout = []
lparz = []

prev = li[0]    
for pos, el in enumerate(li):
    if el == prev:
        lparz.append(pos)
    else:
        lout.append(lparz)
        lparz = [pos,]
    prev = el

lout.append(lparz)
print lout

exits

[[0, 1, 2, 3, 4], [5, 6, 7], [8, 9], [10], [11, 12, 13]]

as needed.

0
source

All Articles