gpt4 book ai didi

Python 切片和负步幅——为什么这些例子明显矛盾?

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:26 25 4
gpt4 key购买 nike

我在这里阅读了很多关于将切片与负步幅相结合的答案,但以下问题仍然让我感到困惑。在几个地方,我看到下图用于说明切片符号的工作原理(指的是间隙,而不是条目):

 +---+---+---+---+
| T | e | s | t |
+---+---+---+---+
0 1 2 3 4
-4 -3 -2 -1

这些例子与上图一致:

>>> "Test"[2:]
'st'

>>> "Test"[-2:]
'st'

但是

>>> "Test"[-2::-1]
'seT'

似乎不一致 - 如果从 -2 分隔符开始并向后计数,为什么 s 也包含在返回的字符串中?

最佳答案

因此,您拥有的心智模型仅对步幅值有用,但在使用负步幅值时无济于事。请改用下图:

  +---+---+---+---+
| T | e | s | t |
+---+---+---+---+
0 1 2 3 4
-5 -4 -3 -2 -1

标记索引的位置,不是边界。

边界模型很好,但只是为了更容易忘记最终索引不包含在结果值中这一事实。通过仅对索引编号并省略结束索引,您可以看到正步幅和负步幅是如何工作的。

具体细节可以看一下Python计算切片方式的官方文档;来自 sequence type notes (注5):

s[i:j:k]
The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

因此,对于您的负步幅,值变为:

i = len(s) - 2 = 2 
j = None = -1 (end for negative strides, *not* len(s) - 1)
k = -1

哪里j是“结束”,这里是 -1,因为那是你在负步中用完字符串的点。然后索引变为:

x0 = i + 0*k = 2
x1 = i + 1*k = 1
x2 = i + 2*k = 0

给你 3 个索引。

关于Python 切片和负步幅——为什么这些例子明显矛盾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19542868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com