Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transform list to list of consecutive elements

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading