Home > Back-end >  How to check if second value of slice() is a certain value?
How to check if second value of slice() is a certain value?

Time:11-23

I have a function that takes in a slice. What I want to do is to check if the end value in this slice is equal to -1. If that is the case, I want to reset the slice to another value. I can't find supporting documentation and do not know how to proceed.

datalist=[None, 'Grey', 'EE20-700', 'EE-42-01', 'EE15-767', 'EE0-70650', 'B&B', 1, 1, 1, 1, 1, '300R', True, 'Nov. 2, 2022', 'Nov. 2, 2022', 1, 1, 1, True, 3]

#If we just apply the given slice_dimensions, the following happens:
slice_dimensions=slice(1, -1)
datalist[slice_dimensions]
['Grey', 'EE20-700', 'EE-42-01', 'EE15-767', 'EE0-70650', 'B&B', 1, 1, 1, 1, 1, '300R', True, 'Nov. 2, 2022', 'Nov. 2, 2022', 1, 1, 1, True]

As you can see this is problematic, because the last element of my list (3) is omitted with the current slice dimension. I have seen many solutions saying I should use len(datalist)-1 or something similar instead, but this is not a workable option because the list lengths differ, and I want to keep it simple. If we can just check if end of slice is equal to -1 and change it to None, the problem is solved:

#If we just apply the given slice_dimensions, the following happens:
slice_dimensions=slice(1, None)
datalist[slice_dimensions]
['Grey', 'EE20-700', 'EE-42-01', 'EE15-767', 'EE0-70650', 'B&B', 1, 1, 1, 1, 1, '300R', True, 'Nov. 2, 2022', 'Nov. 2, 2022', 1, 1, 1, True, 3]

I would like to make a function to do so, but do not know how to proceed, something like this:

def slicer(slice_dimensions):
    if slice_dimensions[1] == -1:  #This part I do not know how to proceed
        slice_dimensions= slice(1, None)
    data_of_interest=datalist[slice_dimensions]
    return(data_of_interest)

How should I proceed in doing so?

CodePudding user response:

You could define a wrapper for slice(). Something like:

def nonwrapping_slice(start=0, stop=None, stride=1):
    if stop is not None and stop < 0 and stride > 0:
        stop = None
    return slice(start, stop, stride)

Then you can call nonwrapping_slice(1, -1) and it will return slice(1, None, 1)

CodePudding user response:

slice object exposes all its parameters as start, stop and step attributes (readonly). So you can just create a new slice, if necessary:

def slicer(objects, slice_dimensions):
    if slice_dimensions.end == -1:
        # Create a copy slice with end replaced with None
        slice_dimensions = slice(slice_dimensions.start, None, slice_dimensions.step)
    return objects[slice_dimensions]

Also, slices have a useful indices method, that takes sequence length as argument and outputs a tuple of actual (start, stop, step) (without None and negative values). You can read more in docs (one screen above this anchor - they do not have own heading with href to an anchor)

  • Related