以负的步幅转到序列开头的扩展切片 [英] Extended slice that goes to beginning of sequence with negative stride

查看:61
本文介绍了以负的步幅转到序列开头的扩展切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我解释我的问题时,请和我在一起.如果您已经了解扩展的切片列表索引,请跳到粗体标题.

Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.

在python中,您可以使用切片符号为列表建立索引.这是一个示例:

In python, you can index lists using slice notation. Here's an example:

>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]

您还可以包括一个跨步,其作用类似于一个步骤":

You can also include a stride, which acts like a "step":

>>> A[0:5:2]
[0, 2, 4]

也可以将步幅设置为负,这意味着将以相反的顺序检索元素:

The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:

>>> A[5:0:-1]
[5, 4, 3, 2, 1]

但是等等!我想看[4, 3, 2, 1, 0].哦,我知道了,我需要减少开始索引和结束索引:

But wait! I wanted to see [4, 3, 2, 1, 0]. Oh, I see, I need to decrement the start and end indices:

>>> A[4:-1:-1]
[]

发生了什么事?它将-1解释为位于数组的末尾,而不是开头.我知道您可以实现以下目标:

What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:

>>> A[4::-1]
[4, 3, 2, 1, 0]

但是您不能在所有情况下都使用它.例如,在已传递索引的方法中.

But you can't use this in all cases. For example, in a method that's been passed indices.

是否存在使用带有负步幅以及包含序列的第一个元素的显式开始和结束索引的扩展切片的良好Python方法?

Is there any good pythonic way of using extended slices with negative strides and explicit start and end indices that include the first element of a sequence?

到目前为止,这是我想出的,但似乎并不令人满意.

This is what I've come up with so far, but it seems unsatisfying.

>>> A[0:5][::-1]
[4, 3, 2, 1, 0]

推荐答案

好吧,我认为这可能和我所理解的一样好.感谢Abgan提出了这个想法.这依赖于以下事实:将片中的None视为缺少的参数.任何人都有更好的东西吗?

Ok, I think this is probably as good as I will get it. Thanks to Abgan for sparking the idea. This relies on the fact that None in a slice is treated as if it were a missing parameter. Anyone got anything better?

def getReversedList(aList, end, start, step):
    return aList[end:start if start!=-1 else None:step]

检查start==-1,而不是0

edit: check for start==-1, not 0

这仍然不是理想的,因为您正在破坏-1的通常行为.似乎这里的问题是应该发生的事情的两个重叠定义.无论谁赢了,都会夺走其他目的的有效调用.

This is still not ideal, because you're clobbering the usual behavior of -1. It seems the problem here is two overlapping definitions of what's supposed to happen. Whoever wins takes away otherwise valid invocations looking for the other intention.

这篇关于以负的步幅转到序列开头的扩展切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆