Skip to content

Instantly share code, notes, and snippets.

@bpeterso2000
Last active August 29, 2015 14:00
Show Gist options
  • Save bpeterso2000/11191112 to your computer and use it in GitHub Desktop.
Save bpeterso2000/11191112 to your computer and use it in GitHub Desktop.
def indices2slices(indices):
"""
convert a list of discrete indices into a minimal list of slices
:returns: [(start1:stop1:step1), (start2:stop2:step2) ...)]
"""
slices = []
if len(indices) == 1:
slices = [indices[0]]
elif len(indices) > 1:
start, stop, step = (indices[0], None, None)
for idx, value in enumerate(indices[1:]):
span = value - indices[idx]
if step and span != step:
slices.append((start, stop, None if step == 1 else step,))
start, stop, step = (value, value, None)
else:
start, stop, step = (start, value, span)
slices.append((start, stop, None if step == 1 else step,))
return slices
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment