list对象的index方法不接受可选参数start

Index methof of list object doesn't accepr optional parameter start

我有一个包含一些可重复元素的列表。
我想找到从特定位置开始(而不是从头开始)的元素的索引。
所以我在列表对象上使用了索引方法。根据文档,它有可选参数启动和停止。

我使用的代码示例:

lst = [5, 1, 2, 3, 4, 5, 6, 7]
index_5 = lst.index(5, start=2)
print(index_5)

当我 运行 这段代码时,我得到了索引方法没有参数 start 的异常。可能是什么问题?

Traceback (most recent call last):
  File "D:/Misc.py", line 2, in <module>
    index_5 = lst.index(5, start=2)
TypeError: index() takes no keyword arguments

作为解决方法,我可以在下面做一些技巧,但如果有使用语言功能的方法,我会更喜欢它。

index_5 = lst[2:].index(5) + 2

根据 documentation index,参数 start 仅缩小搜索范围 space:

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

错误旁边说没有 keyword 个参数,所以你应该使用 positional 个参数。

But signature in builtins.py specified as def index(self, value, start=None, stop=None) so I expected that it is named parameters.

看到这个 answer。它说:

Due to the way the Python C-level APIs developed, a lot of built-in functions and methods don't actually have names for their arguments. Even if the documentation calls the argument default, the function doesn't recognize the name default as referring to the optional second argument. You have to provide the argument positionally.

文档以前在仅位置参数方面表现不佳,但在现代 Python 上,它们正在改进。关键信息是签名中看似不合适的/:

index(value, start=0, stop=9223372036854775807, /)
                                                ^ This is not a typo!

这意味着正斜杠之前的所有参数只是位置参数,不能通过关键字传递。

函数参数列表中的斜杠表示它前面的参数是位置参数。仅位置参数是没有外部可用名称的参数。在调用接受仅位置参数的函数时,参数仅根据其位置映射到参数。

试试这个:

lst.index(5,2)

关于解释,this也可以解释一下:

Many of the builtin functions use only METH_VARARGS which means they don't support keyword arguments. "len" is even simpler and uses an option METH_O which means it gets a single object as an argument. This keeps the code very simple and may also make a slight difference to performance.