简体   繁体   English

遍历从 1 开始的范围的 Pythonic 方式

[英]Pythonic way to iterate through a range starting at 1

Currently if I want to iterate 1 through n I would likely use the following method:目前,如果我想通过n迭代1 ,我可能会使用以下方法:

for _ in range(1, n+1):
    print(_)

Is there a cleaner way to accomplish this without having to reference n + 1 ?有没有更简洁的方法来实现这一点而不必参考n + 1

It seems odd that if I want to iterate a range ordinally starting at 1, which is not uncommon, that I have to specify the increase by one twice:奇怪的是,如果我想迭代一个从 1 开始的范围,这并不罕见,我必须指定两次增加一:

  1. With the 1 at the start of the range. 1在范围的开头。
  2. With the + 1 at the end of the range. + 1在范围的末尾。

From the documentation:从文档中:

range([start], stop[, step])

The start defaults to 0, the step can be whatever you want, except 0 and stop is your upper bound, it is not the number of iterations. start 默认为 0,step 可以是任何你想要的,除了 0 和 stop 是你的上限,它不是迭代次数。 So declare n to be whatever your upper bound is correctly and you will not have to add 1 to it.因此,将 n 声明为您的上限是正确的,并且您不必向其添加 1。

eg例如

>>> for i in range(1, 7, 1): print(i)
... 
1
2
3
4
5
6
>>> for i in range(1, 7, 2): print(i)
... 
1
3
5

A nice feature, is that it works in reverse as well.一个不错的功能是它也可以反向工作。

>>> for i in range(7, 0, -1): print(i)
... 
7
6
5
4
3
2
1

If you aren't using it as an index but for something that can have positive or negative values, it still comes in handy:如果您不将它用作索引,而是用于可以具有正值或负值的东西,它仍然会派上用场:

>>> for i in range(2, -3, -1): print(i)
... 
2
1
0
-1
-2
>>> for i in range(-2, 3, 1): print(i)
... 
-2
-1
0
1
2

range(1, n+1) is not considered duplication, but I can see that this might become a hassle if you were going to change 1 to another number. range(1, n+1)不被视为重复,但我可以看到,如果您要将1更改为另一个数字,这可能会变得很麻烦。

This removes the duplication using a generator:这使用生成器删除重复:

for _ in (number+1 for number in range(5)):
    print(_)

range(1, n+1) is common way to do it, but if you don't like it, you can create your function: range(1, n+1)是常用的方法,但如果你不喜欢它,你可以创建你的 function:

def numbers(first_number, last_number, step=1):
    return range(first_number, last_number+1, step)

for _ in numbers(1, 5):
    print(_)

Not a general answer, but for very small ranges (say, up to five), I find it much more readable to spell them out in a literal:不是一般的答案,但对于非常小的范围(例如,最多五个),我发现用文字拼出它们更具可读性:

for _ in [1,2,3]:
    print _

That's true even if it does start from zero.即使它确实从零开始也是如此。

for i in range(n):
    print(i+1)

This will output:这将 output:

1 
2
...
n    

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

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