首页 > 解决方案 > 我在 Python 官方文档中找不到的一种方法

问题描述

我正在阅读 python 食谱并发现了这个食谱:

如果您有一个切片实例s,您可以通过分别查看它的 、 和 属性来获取有关它的 s.start更多s.stop信息s.step。例如:

>>> a = slice(5, 50, 2)
>>> a.start
5
>>> a.stop
50
>>> a.step
2
>>>

此外,您可以使用其 index(size) 方法将切片映射到特定大小的序列上。这将返回一个元组 (start, stop, step),其中所有值都被适当地限制在边界内(以避免索引时出现 IndexError 异常)。例如:

>>> s = 'HelloWorld'
>>> a.indices(len(s))
(5, 10, 2)
>>> for i in range(*a.indices(len(s))):
... print(s[i])
...
W
r
d

indices()在 Python 官方文档中查找了方法,但找不到。这本书在这里犯错了吗?如果不是,这个方法有什么作用?

标签: python

解决方案


调用help(a)您初始化的切片对象,我发现以下内容 -

 |  indices(...)
 |      S.indices(len) -> (start, stop, stride)
 |
 |      Assuming a sequence of length len, calculate the start and stop
 |      indices, and the stride length of the extended slice described by
 |      S. Out of bounds indices are clipped in a manner consistent with the
 |      handling of normal slices.

推荐阅读