Skip to content

Instantly share code, notes, and snippets.

@numberoverzero
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save numberoverzero/8af84fcefc2c796451c8 to your computer and use it in GitHub Desktop.

Select an option

Save numberoverzero/8af84fcefc2c796451c8 to your computer and use it in GitHub Desktop.
Simple indexing into a list or iterable by name
def build_index(*fields):
'''each arg is (field_name, length) tuple'''
index = type('Index', (object,), {})
start = 0
for field, offset in fields:
s = slice(start, start + offset)
setattr(index, field, s)
start += offset
return index
#=========
# Sample usage
#=========
r = range(30)
fields = [
('first', 3),
('second', 5),
('third', 6)
]
index = build_index(*fields)
print(r[index.first]) # [0, 1, 2]
print(r[index.second]) # [3, 4, 5, 6, 7]
print(r[index.third]) # [8, 9, 10, 11, 12, 13]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment