Skip to content
Advertisement

Python, converting a list of indices to slices

So I have a list of indices,

JavaScript

and want to convert it to this,

JavaScript

this will run on a large number of indices.

Also, this technically isn’t for slices in python, the tool I am working with is faster when given a range compared to when given the individual ids.

The pattern is based on being in a range, like slices work in python. So in the example, the 1 and 2 are dropped because they are already included in the range of 0 to 3. The 5 would need accessed individually since it is not in a range, etc. This is more helpful when a large number of ids get included in a range such as [0, 5000].

Advertisement

Answer

Since you want the code to be fast, I wouldn’t try to be too fancy. A straight-forward approach should perform quite well:

JavaScript

Admittedly, that’s doesn’t look too nice, but I expect the nicer solutions I can think of to perform worse. (I did not do a benchmark.)

Here is s slightly nicer, but slower solution:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement