Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

python - 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:

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

Is there a cleaner way to accomplish this without having to reference 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. With the 1 at the start of the range.
  2. With the + 1 at the end of the range.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. So declare n to be whatever your upper bound is correctly and you will not have to add 1 to it.

e.g.

>>> 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...