为什么范围(开始,结束)不包括结束? [英] Why does range(start, end) not include end?

查看:69
本文介绍了为什么范围(开始,结束)不包括结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>范围(1,11)

给你

[1,2,3,4,5,6,7,8,9,10]

为什么不是 1-11?

他们是随机决定这样做还是有一些我没有看到的价值?

解决方案

因为调用返回 [0,1,2,3,4,5,6,7,8,9] 包含 10 个元素,等于 len(range(0, 10)).请记住,程序员更喜欢基于 0 的索引.

另外,请考虑以下常见代码片段:

for i in range(len(li)):经过

你能看出如果 range() 正好达到 len(li) 会出现问题吗?程序员需要明确地减去 1.这也遵循了程序员更喜欢 for(int i = 0; i < 10; i++) 而不是 for(int i = 0;i <= 9; i++).

如果您经常调用以 1 开头的 range,您可能需要定义自己的函数:

<预><代码>>>>定义范围1(开始,结束):...返回范围(开始,结束+1)...>>>范围 1(1, 10)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> range(1,11)

gives you

[1,2,3,4,5,6,7,8,9,10]

Why not 1-11?

Did they just decide to do it like that at random or does it have some value I am not seeing?

解决方案

Because it's more common to call range(0, 10) which returns [0,1,2,3,4,5,6,7,8,9] which contains 10 elements which equals len(range(0, 10)). Remember that programmers prefer 0-based indexing.

Also, consider the following common code snippet:

for i in range(len(li)):
    pass

Could you see that if range() went up to exactly len(li) that this would be problematic? The programmer would need to explicitly subtract 1. This also follows the common trend of programmers preferring for(int i = 0; i < 10; i++) over for(int i = 0; i <= 9; i++).

If you are calling range with a start of 1 frequently, you might want to define your own function:

>>> def range1(start, end):
...     return range(start, end+1)
...
>>> range1(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

这篇关于为什么范围(开始,结束)不包括结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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