Best way to loop over a python string backwards

后端 未结 11 1874
無奈伤痛
無奈伤痛 2020-12-03 02:16

What is the best way to loop over a python string backwards?

The following seems a little awkward for all the need of -1 offset:

string = \"trick or          


        
11条回答
  •  时光取名叫无心
    2020-12-03 03:18

    Less code is usually faster in Python. Luckily, you don't have to guess:

    python -mtimeit -s"s='x'*100000" "for x in s[::-1]: pass"
    100 loops, best of 3: 1.99 msec per loop
    
    python -mtimeit -s"s='x'*100000" "for x in reversed(s): pass"
    1000 loops, best of 3: 1.97 msec per loop
    
    python -mtimeit -s"s='x'*100000" "for i in xrange(len(s)-1, 0-1, -1): s[i]"
    100 loops, best of 3: 4.95 msec per loop
    

    So the shorter code is a bit faster, but it comes with a memory overhead.

提交回复
热议问题