class slice(start, stop[, step])
返回一个表示由范围指定的索引集的片对象(开始、停止、步骤)。
代码中的内容是什么,为什么切片类init甚至允许一个列表作为它的参数?
print(slice([1,3]))
---
slice(None, [1, 3], None)
print(slice(list((1,3))))
---
slice(None, [1, 3], None) # why stop is list?
hoge = [1,2,3,4]
_s = slice(list((1,3)))
print(hoge[_s])
--------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-59-1b2df30e9bdf> in <module>
1 hoge = [1,2,3,4]
2 _s = slice(list((1,3)))
----> 3 print(hoge[_s])
TypeError: slice indices must be integers or None or have an __index__ method
厄普代
多亏了Selcuk的回答。
static PyObject *
slice_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
PyObject *start, *stop, *step;
start = stop = step = NULL;
if (!_PyArg_NoKeywords("slice", kw))
return NULL;
if (!PyArg_UnpackTuple(args, "slice", 1, 3, &start, &stop, &step))
return NULL;
/* This swapping of stop and start is to maintain similarity with
range(). */
if (stop == NULL) {
stop = start; // <-----
start = NULL;
}
return PySlice_New(start, stop, step); // PySlice_New in L110 in the same file
}
发布于 2020-12-23 04:20:22
来自文献资料
片对象具有只读数据属性
start
、stop
和step
,它们仅返回参数值(或它们的默认值)。他们没有其他明确的功能..。
因此,它们只是一个虚拟的对象,它保存着你传递给它们的任何东西。您甚至可以传递字符串或其他对象:
my_slice = slice("foo", "bar", "baz")
..。然而,它们被数值Python和其他第三方扩展所使用。
第三方扩展的任务是验证start
、stop
和step
值是否有任何意义。
还可以看到CPython实现。
当您只传递一个参数时,假设它是stop
值。这就是为什么将start
和step
值设置为None
的原因。
class slice(stop)
class slice(start, stop[, step])
https://stackoverflow.com/questions/65418944
复制相似问题