为什么切片和范围上限是互斥的? [英] Why are slice and range upper-bound exclusive?

查看:68
本文介绍了为什么切片和范围上限是互斥的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我不是在问是否 slice()range()的上限stop参数是排他性的,还是如何使用这些功能. /p>

rangeslice函数的调用以及切片符号[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 stopargument of slice()and range() is exclusive or how to use these functions.

Calls to the rangeand slicefunctions, 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 stopequal 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:] equals s.

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] is 2.

I think we can assume that the range functions act the same for consistency.

这篇关于为什么切片和范围上限是互斥的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆