为什么切片和范围上限是互斥的? [英] Why are slice and range upper-bound exclusive?
问题描述
免责声明:我不是在问是否 slice()
和range()
的上限stop
参数是排他性的,还是如何使用这些功能. /p>
对range
和slice
函数的调用以及切片符号[start:stop]
均指整数集.
range([start], stop[, step])
slice([start], stop[, step])
在所有这些中,排除了stop
整数.
我想知道为什么这样设计语言.
当start
等于0或省略时,是否使stop
等于表示的整数集中的元素数?
有吗?
for i in range(start, stop):
看起来像下面的C代码吗?
for (i = start ; i < stop; i++) {
文档表示这具有一些有用的属性:
word[:2] # The first two characters
word[2:] # Everything except the first two characters
这是切片操作的一个有用的不变式:
s[:i] + s[i:]
等于s
.对于非负索引,如果切片的长度都在索引范围之内,则它们的长度就是索引的差.例如,
word[1:3]
的长度是2
.
我认为我们可以假设范围函数的作用相同以保持一致性.
Disclaimer: I am not asking if the upper-bound stop
argument of slice()
and range()
is exclusive or how to use these functions.
Calls to the range
and slice
functions, as well as the slice notation [start:stop]
all refer to sets of integers.
range([start], stop[, step])
slice([start], stop[, step])
In all these, the stop
integer is excluded.
I am wondering why the language is designed this way.
Is it to make stop
equal to the number of elements in the represented integer set when start
equals 0 or is omitted?
Is it to have:
for i in range(start, stop):
look like the following C code?
for (i = start ; i < stop; i++) {
The documentation implies this has a few useful properties:
word[:2] # The first two characters
word[2:] # Everything except the first two characters
Here’s a useful invariant of slice operations:
s[:i] + s[i:]
equalss
.For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of
word[1:3]
is2
.
I think we can assume that the range functions act the same for consistency.
这篇关于为什么切片和范围上限是互斥的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!