- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在这里阅读了很多关于将切片与负步幅相结合的答案,但以下问题仍然让我感到困惑。在几个地方,我看到下图用于说明切片符号的工作原理(指的是间隙,而不是条目):
+---+---+---+---+
| 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 ofs
fromi
toj
with stepk
is defined as the sequence of items with indexx = i + n*k
such that0 <= n < (j-i)/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
). Ifi
orj
is greater thanlen(s)
, uselen(s)
. Ifi
orj
are omitted orNone
, they become “end” values (which end depends on the sign ofk
). Note,k
cannot be zero. Ifk
isNone
, it is treated like1
.
因此,对于您的负步幅,值变为:
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/
我不确定哪种结构布局最适合我的应用程序:共享、打包、std140、std430。我并不是要求对每个信息进行解释,这些信息很容易找到,只是很难弄清楚每个信息对供应商兼容性/性能的影响。如果 shared
如何在 Swift 中获取特定数字类型的最小值(跨度)?我的意思是,最短的非零步幅。例如 1 代表 Int,0.00...001 代表 Double 等... 最佳答案 这已经在单独的评论中得到了部分
有没有办法告诉 numpy 在写入 python pickle 文件时保留非标准步幅? >>> # Create an array with non-standard striding >>> x =
我将图像存储为 2d numpy 数组(可能是多维)。 我可以在那个反射(reflect)二维滑动窗口的数组上创建一个 View ,但是当我 reshape 它以使每一行都是一个扁平化的窗口(行是窗口
我是一名优秀的程序员,十分优秀!