Home > Blockchain >  Transform list to list of consecutive elements
Transform list to list of consecutive elements

Time:10-24

Any idea how i could do the following in python >3.7 ?

a = ["a","b","c","c","a","a","a"]
b = F(a) => [[0],[1],[2,3],[4,5,6]]

The use case is a list with roughly 10e6 elements.
Thx

CodePudding user response:

IIUC, one approach:

from itertools import groupby, count

a = ["a","b","c","c","a","a","a"]
counter = count()

res = [[next(counter) for _ in vs] for _, vs in groupby(a)]
print(res)

Output

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

An alternative using enumerate:

from itertools import groupby
from operator import itemgetter

a = ["a","b","c","c","a","a","a"]
res = [[v for v, _ in vs] for k, vs in groupby(enumerate(a), key=itemgetter(1))]
print(res)

CodePudding user response:

a = ["a","b","c","c","a","a","a"]
res = []
prev_item = None
for i, item in enumerate(a):
    if item == prev_item:
        res[-1].append(i)
    else:
        res.append([i])
    prev_item = item
  • Related