从元组创建范围 (slice.indices())
Create range from tuple (slice.indices())
在 Python 2.3 文档的 this page 底部,它说:
slice objects now have a method indices(length) which, given the length of a sequence, returns a (start, stop, step) tuple that can be passed directly to range()
这是一些测试代码:
s = slice(0, 10)
r = range(s.indices(10))
它抛出 TypeError
:
TypeError: range() integer end argument expected, got tuple.
为什么这不起作用?
在我的用例中,range()
在 library 中被调用,我需要提供这样使用的 slice
。
试试这个:
r = range(*s.indices(10))
解释:range()
需要最多三个整数作为参数,因此我们需要解压返回的整数元组通过 indices()
使用 *
,splat 运算符。
在 Python 2.3 文档的 this page 底部,它说:
slice objects now have a method indices(length) which, given the length of a sequence, returns a (start, stop, step) tuple that can be passed directly to range()
这是一些测试代码:
s = slice(0, 10)
r = range(s.indices(10))
它抛出 TypeError
:
TypeError: range() integer end argument expected, got tuple.
为什么这不起作用?
在我的用例中,range()
在 library 中被调用,我需要提供这样使用的 slice
。
试试这个:
r = range(*s.indices(10))
解释:range()
需要最多三个整数作为参数,因此我们需要解压返回的整数元组通过 indices()
使用 *
,splat 运算符。