Disclaimer: I misread the question and thought you wanted to go from the slice notation to the set version, this doesn't actually answer your question but I figured it was worth leaving posted. It also seems that numpy._r
does the same (or at least very similar) thing.
First off note that if you are using python 3.5+ PEP 3132 gives is an option to use the *unpacking
method in set literals:
>>> {*range(1,9), *range(11,15,2), *range(45,47), 3467}
{1, 2, 3, 4, 5, 6, 7, 8, 11, 3467, 13, 45, 46}
Otherwise the notation 11:15:2
is only used when __getitem__
or __setitem__
is used on an object, so you would just need to set up an object that will generate your sets:
def slice_to_range(slice_obj):
assert isinstance(slice_obj, slice)
assert slice_obj.stop is not None, "cannot have stop of None"
start = slice_obj.start or 0
stop = slice_obj.stop
step = slice_obj.step or 1
return range(start,stop,step)
class Slice_Set_Creator:
def __getitem__(self,item):
my_set = set()
for part in item:
if isinstance(part,slice):
my_set.update(slice_to_range(part))
else:
my_set.add(part)
return my_set
slice_set_creator = Slice_Set_Creator()
desired_set = slice_set_creator[1:9:1,11:15:2,45:47:1,3467]
>>> desired_set
{1, 2, 3, 4, 5, 6, 7, 8, 11, 3467, 13, 45, 46}