Python range() with negative strides

前端 未结 7 973

Is there a way of using the range() function with stride -1?

E.g. using range(10, -10) instead of the square-bracketed values below?

<
相关标签:
7条回答
  • 2020-12-09 15:14

    In addition to the other good answers, there is an alternative:

    for y in reversed(range(-10, 11)):
    

    See the documentation for reversed().

    0 讨论(0)
  • 2020-12-09 15:16

    You may notice that the range function works only in ascending order without the third parameter. If you use without the third parameter in the range block, it will not work.

    for i in range(10,-10)
    

    The above loop will not work. For the above loop to work, you have to use the third parameter as negative number.

    for i in range(10,-10,-1) 
    
    0 讨论(0)
  • 2020-12-09 15:18

    If you prefer create list in range:

    numbers = list(range(-10, 10))
    
    0 讨论(0)
  • 2020-12-09 15:21

    Yes, by defining a step:

    for i in range(10, -11, -1):
        print(i)
    
    0 讨论(0)
  • 2020-12-09 15:22

    To summarize, these 3 are the best efficient and relevant to answer approaches I believe:

    first = list(x for x in range(10, -11, -1))
    
    second = list(range(-10, 11))
    
    third = [x for x in reversed(range(-10, 11))]
    

    Alternatively, NumPy would be more efficient as it creates an array as below, which is much faster than creating and writing items to the list in python. You can then convert it to the list:

    import numpy as np
    
    first = -(np.arange(10, -11, -1))
    

    Notice the negation sign for first.

    second = np.arange(-10, 11)
    

    Convert it to the list as follow or use it as numpy.ndarray type.

    to_the_list = first.tolist()
    
    0 讨论(0)
  • 2020-12-09 15:25

    Yes, however you'll need to specify that you want to step backwards by setting the step argument to -1.

    Use:

    for y in range(10, -10, -1)

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