Retrieve length of slice from slice object in Python

后端 未结 5 1256
灰色年华
灰色年华 2021-01-04 03:05

The title explains itself, how to get 2 out of the object

slice(0,2)

The documentation is somewhat confusing, or it is the wrong one

<
5条回答
  •  醉话见心
    2021-01-04 03:25

    a simplified approach with asserts

    The length depends on the target object, which is sliced. But one can define a maximum length.

    Example

    define your maximum length function like this

    def slice_len_max(s):
        assert (s.start is not None)
        assert (s.stop is not None)
        step = 1
        if s.step is not None:
            step = s.step
        return max((s.stop - s.start) // step, 1)
    

    and check the output

    >>> slice_len_max(slice(0, 10))
    10
    >>> slice_len_max(slice(0, 10, 2))
    5
    >>> slice_len_max(slice(0, 10, 3))
    3
    >>> slice_len_max(slice(0, 10, 10))
    1
    >>> slice_len_max(slice(0, 10, 100))
    1
    >>> slice_len_max(slice(3))
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 2, in slice_len_max
    AssertionError
    

    The last call crashes, as the slice has no start attribute defined.

提交回复
热议问题