简体   繁体   English

范围如何与 python 中的 for 循环配合使用

[英]How range works with for loop in python

for i in range(1,4,-1):
    print(i)

Here, "i" will be initialized as "1" which lies in [1, 4), So it should print 1, but it doesn't print anything.在这里,“i”将被初始化为位于 [1, 4) 中的“1”,所以它应该打印 1,但它不打印任何东西。 Why?为什么?

Here your step value is negative在这里,您的步长值为负

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.对于正步骤,范围 r 的内容由公式 r[i] = start + step*i 确定,其中 i >= 0 且 r[i] < stop。

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.对于负步长,范围的内容仍然由公式 r[i] = start + step*i 确定,但约束条件是 i >= 0 和 r[i] > stop。

The first value would be 1 + (-1) * 0 = 1, which is less than your step value (4) and this fails the second constraint.第一个值将是1 + (-1) * 0 = 1,它小于您的步长值 (4),这会导致第二个约束失败。

so if you go through the formula, its obvious nothing would get printed - Reference因此,如果您通过公式 go ,则显然不会打印任何内容- 参考

In order to make it work you should have: range(4, 1, -1).为了使它工作,你应该有:range(4, 1, -1)。

As said on the documentation:如文档所述:

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.对于正步骤,范围 r 的内容由公式 r[i] = start + step*i 确定,其中 i >= 0 且 r[i] < stop。

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.对于负步长,范围的内容仍然由公式 r[i] = start + step*i 确定,但约束条件是 i >= 0 和 r[i] > stop。

According to this part of the documentation :根据文档的这一部分

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.对于负步长,范围的内容仍然由公式 r[i] = start + step*i 确定,但约束条件是 i >= 0 和 r[i] > stop。

Your first value would be 1 + (-1) * 0 = 1, which is less than your stop value of 4. So the second constraint applies, and this value isn't kept.您的第一个值将是1 + (-1) * 0 = 1,它小于您的停止值 4。因此应用了第二个约束,并且不保留此值。 Your range is empty.你的范围是空的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM