Python range() with negative strides

前端 未结 7 1066

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: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()
    

提交回复
热议问题