What are the default values set to in a slice?
我看了一下关于why-do-list-1-not-equal-listlenlist-1和python中的默认切片索引的顶级答案,了解切片中默认值的设置。两个最重要的答案都参考以下文档:
考虑到
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.
假设我有以下代码:
1 2 3 4 5 6 | s ="hello" forward_s = s[::1] print(forward_s) # =>"hello" backward_s = s[::-1] print(backward_s) # =>"olleh" |
我知道,如果省略了索引,那么python将其视为在这些地方使用了
例如,以下内容也会反转字符串:
1 | reversed_str = s[-1:-6:-1] |
那么,当
默认值为
1 2 3 4 5 6 | class Sliceable(object): def __getitem__(self, slice): print(slice) Sliceable()[::] >>> slice(None, None, None) |
这与事实无关,即
The
start ,stop , andstep parameters are used as the values of the slice object attributes of the same names. Any of the values may beNULL , in which case theNone will be used for the corresponding attribute.
由可切片的对象来理解默认值。约定是使用第一个元素、最后一个元素、内部集合实现的最小步进:
1 2 3 4 5 | l = [1, 2, 3] l[slice(None, None, None]) >>> [1, 2, 3] s[None:None:None]) >>> [1, 2, 3] |
负步进将导致默认的
1 2 3 4 5 | s = 'abc' s[slice(None, None, -1)] >>> 'cba' s[::-1] >>> 'cba' |
注意,这并不意味着一个简单的值翻转,
记录如下:
s[i:j:k] The slice of
s 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 ). Whenk is positive,i andj are reduced tolen(s) if they are greater. Whenk is negative,i andj are reduced tolen(s) - 1 if they are greater. Ifi orj are omitted or None, they become"end" values (which end depends on the sign ofk ). Note,k cannot be zero. Ifk isNone , it is treated like1 .