3 ms·
Discontinuous Ranges in Python
- eesmith 7y agoI thought something like: >>> for x in multirange[1:5, 8:12:2]: ... print(x) ... 1 2 3 4 8 10 would be interesting, so I coded it up: class Multirange: def __getitem__(self, ranges): if not isinstance(ranges, tuple): ranges = (ranges,) for term in ranges: if not isinstance(term, slice): raise ValueError("Only slices are allowed, not %r" % (term,)) if term.start is None: raise ValueError("Missing slice start: %r" % (term,)) if term.stop is None: raise ValueError("Missing slice end: %r" % (term,)) step = term.step if step is None: step = 1 elif step == 0: raise ValueError("Slice step cannot be zero: %r" % (term,)) yield from range(term.start, term.stop, step) multirange = Multirange() Too many special cases, and requires the [] notation, so I decided I didn't like it.