Pythonic way to iterate through a range starting at 1

后端 未结 5 803
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 16:04

Currently if I want to iterate 1 through n I would likely use the following method:

for _ in rang         


        
相关标签:
5条回答
  • 2021-01-01 16:26
    for i in range(n):
        print(i+1)
    

    This will output:

    1 
    2
    ...
    n    
    
    0 讨论(0)
  • 2021-01-01 16:28

    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.

    0 讨论(0)
  • 2021-01-01 16:28

    range(1, n+1) is common way to do it, but if you don't like it, you can create your function:

    def numbers(first_number, last_number, step=1):
        return range(first_number, last_number+1, step)
    
    for _ in numbers(1, 5):
        print(_)
    
    0 讨论(0)
  • 2021-01-01 16:38

    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.

    This removes the duplication using a generator:

    for _ in (number+1 for number in range(5)):
        print(_)
    
    0 讨论(0)
  • 2021-01-01 16:40

    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.

    0 讨论(0)
提交回复
热议问题