在Python中反转任意切片

问题描述 投票:3回答:5

我正在寻找一种关于如何在Python中反转切片的通用方法。我读了这篇综合文章,其中有几个关于切片如何工作的很好的解释:Understanding Python's slice notation

然而,我无法弄清楚如何计算反向切片的通用规则,反向切片以相反的顺序寻址完全相同的元素。我真的很惊讶没有找到这样做的内置方法。

我正在寻找的是一个方法reversed_slice这样工作与任意startstopstep值包括负值:

>>> import numpy as np
>>> a = np.arange(30)
>>> s = np.s_[10:20:2]
>>> a[s]
array([10, 12, 14, 16, 18])
>>> a[reversed_slice(s,len(a))]
array([18, 16, 14, 12, 10])

我尝试但不起作用的是:

def reversed_slice(slice_, len_):
    """
    Reverses a slice (selection in array of length len_), 
    addressing the same elements in reverse order.
    """
    assert isinstance(slice_, slice)
    instart, instop, instep = slice_.indices(len_)
    if instep > 0:
        start, stop, step = instop - 1, instart - 1, -instep
    else:
        start, stop, step = instop + 1, instart + 1, -instep
    return slice(start, stop, step)

这适用于1的步骤,当最后一个被寻址的元素与stop-1重合时。对于其他情况,它不会:

>>> import numpy as np
>>> a = np.arange(30)
>>> s = np.s_[10:20:2]
>>> a[s]
array([10, 12, 14, 16, 18])
>>> a[reversed_slice(s,len(a))]
array([19, 17, 15, 13, 11])

所以我似乎错过了像(stop - start) % step这样的关系。非常感谢任何有关如何编写通用方法的帮助。

笔记:

  • 我知道还有其他可能性来获得具有相同元素的序列,例如调用reversed(a[s])。这不是一个选项,因为我需要反转切片本身。原因是我在h5py数据集上工作,这些数据集不允许切片中的负step值。
  • 一种简单但不是很优雅的方式是使用坐标列表,即a[list(reversed(range(*s.indices(len(a)))))]。由于h5py要求列表中的索引必须按递增顺序给出,因此这也不是一种选择。
python slice numpy-slicing
5个回答
1
投票

我只想使用这个问题的答案,但是在测试中发现仍有一些案例会默默地给出错误的结果 -

从其他答案开发的reverse_slice函数的以下定义似乎正确涵盖了这些情况 -

def reversed_slice(s, len_):
    """
    Reverses a slice selection on a sequence of length len_, 
    addressing the same elements in reverse order.
    """
    assert isinstance(s, slice)
    instart, instop, instep = s.indices(len_)

    if (instop < instart and instep > 0) or (instop > instart and instep < 0) \
      or (instop == 0 and instart == 0) :
        return slice(0,0,None)

    overstep = abs(instop-instart) % abs(instep)

    if overstep == 0 :
        overstep = abs(instep)

    if instep > 0:
        start = instop - overstep
        stop = instart - 1
    else :
        start = instop + overstep
        stop = instart + 1

    if stop < 0 :
        stop = None

    return slice(start, stop, -instep)

3
投票

您可以为step指定负值。

>>> s = np.s_[20-2:10-2:-2]
>>> a[s]
array([18, 16, 14, 12, 10])

所以你可以按如下方式构建reversed_slice函数

>>> def reversed_slice(s):
...     """
...     Reverses a slice 
...     """
...     m = (s.stop-s.start) % s.step or s.step
...     return slice(s.stop-m, s.start-m, -s.step)
... 
>>> a = np.arange(30)
>>> s = np.s_[10:20:2]
>>> a[reversed_slice(s)]
array([18, 16, 14, 12, 10])
>>> 
>>> a[reversed_slice(reversed_slice(s))]
array([10, 12, 14, 16, 18])
>>> 

0
投票

到目前为止,我也没有找到任何内置,但即使是消极的步骤也是如此:

def invert_slice(start, stop, step=1):
    distance = stop - start
    step_distance = distance // step
    expected_distance = step_distance * step

    if expected_distance != distance:
        expected_distance += step

    new_start = start + expected_distance - step
    new_stop = start - step

    return slice(new_start, new_stop, -step)

这给了你

>>> import numpy as np
>>> a = np.arange(30)
>>> s = np.s_[24:10:-1]
>>> expected = list(reversed(a[s]))

[18, 16, 14, 12, 10]

>>> # resulting slice
>>> result = invert_slice(s.start, s.stop, s.step)

切片(18,8,-2)

>>> assert np.allclose(expected, a[result]), "Invalid Slice %s" % result
>>> a[result]

[18 16 14 12 10]他们是平等的;-)


0
投票

你用start/stop数学犯了一些错误:

overstep = abs(instop-instart) % abs(instep)
if overstep == 0 :
    overstep = abs(instep)

if instep > 0:
    start = instop - overstep
    stop = instart - 1
else :
    start = instop + overstep
    stop = instart + 1

step = -instep

一旦你把它放在你的代码中,一切都应该工作得很好。


0
投票

我找到了一个基于Sunitha答案的工作解决方案(编辑:还实施了Warwick的答案):

def reversed_slice(s, len_):
    """
    Reverses a slice selection on a sequence of length len_, 
    addressing the same elements in reverse order.
    """
    assert isinstance(s, slice)
    instart, instop, instep = s.indices(len_)

    if (instop < instart and instep > 0) or (instop > instart and instep < 0) \
            or (instop == 0 and instart == 0):
        return slice(0, 0, None)

    m = (instop - instart) % instep or instep

    if instep > 0 and instart - m < 0:
        outstop = None
    else:
        outstop = instart - m
    if instep < 0 and instop - m > len_:
        outstart = None
    else:
        outstart = instop - m

    return slice(outstart, outstop, -instep)

它使用slice.indices(len)方法扩展功能,因此它也可以与切片中的None条目一起使用,例如与[::-1]。使用if条款避免了边界问题。

此解决方案仅在提供要解决的序列长度时起作用。我认为没有办法解决这个问题。如果有,或者有更简单的方法,我愿意接受建议!

© www.soinside.com 2019 - 2024. All rights reserved.