Skip to content

Instantly share code, notes, and snippets.

@InbarRose
Last active August 29, 2015 14:19
Show Gist options
  • Save InbarRose/67af342aa32a4e241212 to your computer and use it in GitHub Desktop.
Save InbarRose/67af342aa32a4e241212 to your computer and use it in GitHub Desktop.
hyperslice.py
from operator import itemgetter
def hyperslice(iterable, *args):
if len(args) == 1 and isinstance(args[0], str):
return itemgetter(*map(slice_or_index, args[0].split(',')))(iterable)
elif args:
return itemgetter(*args)(iterable)
else:
return iterable
def slice_or_index(s):
return slice(*map(int, s.split(':'))) if ':' in s else int(s)
## Examples
# >>> hyperslice(range(10))
# >>> hyperslice(range(10))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>> hyperslice(range(10), 1)
# >>> hyperslice(range(10), '1')
# 1
# >>> hyperslice(range(10), slice(1,3))
# >>> hyperslice(range(10), '1:3')
# [1, 2]
# >>> hyperslice(range(10), 1, slice(3,6))
# >>> hyperslice(range(10), '1,3:6')
# (1, [3, 4, 5])
# >>> hyperslice(range(10), 1, slice(3,6), 8)
# >>> hyperslice(range(10), '1,3:6,8')
# (1, [3, 4, 5], 8)
# >>> hyperslice(range(10), 1, slice(2,7,3), 8)
# >>> hyperslice(range(10), '1,2:7:3,8')
# (1, [2, 5], 8)
# >>> hyperslice(range(10), 1, slice(4,1,-1), 8, 3, slice(-3,2,-2))
# >>> hyperslice(range(10), '1,4:1:-1,8,3,-3:2:-2')
# (1, [4, 3, 2], 8, 3, [7, 5, 3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment