Last active
August 29, 2015 14:06
-
-
Save numberoverzero/8af84fcefc2c796451c8 to your computer and use it in GitHub Desktop.
Simple indexing into a list or iterable by name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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