Print a list in reverse order with range()?

前端 未结 19 698
长发绾君心
长发绾君心 2020-11-30 17:09

How can you produce the following list with range() in Python?

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
相关标签:
19条回答
  • 2020-11-30 17:43

    You can do printing of reverse numbers with range() BIF Like ,

    for number in range ( 10 , 0 , -1 ) :
        print ( number ) 
    

    Output will be [10,9,8,7,6,5,4,3,2,1]

    range() - range ( start , end , increment/decrement ) where start is inclusive , end is exclusive and increment can be any numbers and behaves like step

    0 讨论(0)
  • 2020-11-30 17:45

    i believe this can help,

    range(5)[::-1]
    

    below is Usage:

    for i in range(5)[::-1]:
        print i 
    
    0 讨论(0)
  • 2020-11-30 17:47

    For those who are interested in the "efficiency" of the options collected so far...

    Jaime RGP's answer led me to restart my computer after timing the somewhat "challenging" solution of Jason literally following my own suggestion (via comment). To spare the curious of you the downtime, I present here my results (worst-first):

    Jason's answer (maybe just an excursion into the power of list comprehension):

    $ python -m timeit "[9-i for i in range(10)]"
    1000000 loops, best of 3: 1.54 usec per loop
    

    martineau's answer (readable if you are familiar with the extended slices syntax):

    $ python -m timeit "range(10)[::-1]"
    1000000 loops, best of 3: 0.743 usec per loop
    

    Michał Šrajer's answer (the accepted one, very readable):

    $ python -m timeit "reversed(range(10))"
    1000000 loops, best of 3: 0.538 usec per loop
    

    bene's answer (the very first, but very sketchy at that time):

    $ python -m timeit "range(9,-1,-1)"
    1000000 loops, best of 3: 0.401 usec per loop
    

    The last option is easy to remember using the range(n-1,-1,-1) notation by Val Neekman.

    0 讨论(0)
  • 2020-11-30 17:49

    Using without [::-1] or reversed -

    def reverse(text):
        result = []
        for index in range(len(text)-1,-1,-1):
            c = text[index]
            result.append(c)
        return ''.join(result)
    
    print reverse("python!")
    
    0 讨论(0)
  • 2020-11-30 17:50

    You could use range(10)[::-1] which is the same thing as range(9, -1, -1) and arguably more readable (if you're familiar with the common sequence[::-1] Python idiom).

    0 讨论(0)
  • 2020-11-30 17:51

    You don't necessarily need to use the range function, you can simply do list[::-1] which should return the list in reversed order swiftly, without using any additions.

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