[英]slicing tuple out of index in a form of x[0:4:-1]
x = (1, 2, 3, 4)
Here, x[0:4:-1]
gives an empty tuple
()
. 在这里,
x[0:4:-1]
给出一个空的tuple
()
。 Why is this happening? 为什么会这样呢? I thought it would just give a reversed tuple
(4,3,2,1)
... 我认为
(4,3,2,1)
会给一个反向元组(4,3,2,1)
...
You're asking for all of the values starting at 0, ending before 4, counting by -1 at a time. 您需要所有从0开始,在4之前结束的值,一次以-1计数。 That's no values.
那没有价值。
What you want to do is start at 3, end before -1, counting by -1 at a time. 您想要做的是从3开始,在-1之前结束,一次以-1计数。 Except… you can't put
-1
in there, because that means "1 from the end". 除了…您不能在其中放入
-1
,因为那意味着“从末尾开始1”。 So, you have to write "start at 3, end when you've exhausted the whole sequence, counting by -1 at a time", like this: 因此,您必须编写“从3开始,在用尽整个序列时结束,一次以-1计数”,如下所示:
x[3::-1]
Or, more simply: 或者,更简单地说:
x[::-1]
It may help your understanding to turn the slice into an explicit loop. 将切片变成显式循环可能会有助于您的理解。 It looks something like this:
看起来像这样:
def slicify(sequence, start, end, step):
if start < 0: start += len(sequence)
if end < 0: end += len(sequence)
result = []
while (start < end if step > 0 else start > end):
result.append(sequence[start])
start += step
return result
But this is only roughly correct. 但这仅是大致正确的。 The exact definition is in the documentation under Sequence Types , under note 5:
确切的定义在文档中“ 序列类型 ”下的注释5中:
The slice of
s
fromi
toj
with stepk
is defined as the sequence of items with indexx = i + n*k
such that0 <= n < (ji)/k
.的切片
s
从i
到j
与步骤k
被定义为与索引项的序列x = i + n*k
,使得0 <= n < (ji)/k
。 In other words, the indices arei
,i+k
,i+2*k
,i+3*k
and so on, stopping whenj
is reached (but never includingj
).换句话说,索引是
i
,i+k
,i+2*k
,i+3*k
等,当达到j
时停止(但不包括j
)。 Ifi
orj
is greater thanlen(s)
, uselen(s)
.如果
i
或j
大于len(s)
,请使用len(s)
。 Ifi
orj
are omitted orNone
, they become “end” values (which end depends on the sign ofk
).如果省略
i
或j
或None
,它们将成为“结束”值(该结束取决于k
的符号)。 Note,k
cannot be zero.注意,
k
不能为零。 Ifk
isNone
, it is treated like1
.如果
k
为None
,则将其视为1
。
You'd need to either omit the start and end, or reverse the start and end: 您需要省略起点和终点,或者颠倒起点和终点:
x[::-1] # (4, 3, 2, 1)
x[3:0:-1] # (4, 3, 2)
x[3::-1] # (4, 3, 2, 1)
x[3:-5:-1] # (4, 3, 2, 1)
The end point is not included, so slicing with [3:0:-1]
only returns three elements. 端点不包括在内,因此使用
[3:0:-1]
切片只会返回三个元素。 The last example uses a negative value to be subtracted from the length of the tuple to end up with endpoint -1
. 最后一个示例使用一个负值从元组的长度中减去,以终结点
-1
结束。
Using a negative stride means Python wants to count backwards, and starting at 0 you'll never get to 4. 使用负的步幅表示Python希望倒数,从0开始,您永远不会达到4。
Note that the Python slice syntax applies to more than just tuples; 请注意,Python slice语法不仅适用于元组,还适用于其他语法。 strings and lists support the exact same syntax.
字符串和列表支持完全相同的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.