Multiple Slices With Python

You can slice twice and join them.

listing[0:3] + listing[4:5]

If you have the index numbers of the slices you need you can just grab them with a loop contained in a list.

index_nums = [0,2,4]
output = [listing[val] for val in index_nums]

This will return [4,24,46]


With a class, you can do this

class Listing():
    def __init__(self, *args):
        self.array = args
    def __getitem__(self, slices):
        return sum((self.array[s] for s in slices), ())

listing = Listing(4, 22, 24, 34, 46, 56)
listing[0:3, 4:5]   # (4, 22, 24, 46)

The constructs sum((...), ()) joins the tuples (()+()+()) and thus flattens the output.

update

A version that returns a list instead of a tuple, and that handles also single slice (e.g. [0] or [0:1])

class Listing(list):
    def __getitem__(self, s):
        get = super(Listing, self).__getitem__
        return sum(map(get,s), []) if hasattr(s,'__iter__') else get(s)

listing = Listing([4, 22, 24, 34, 46, 56])
listing[0:3, 4:5]   # [4, 22, 24, 46]

Tags:

Python