“”.join(reversed(val)) vs val[::-1]…which is pythonic?

前端 未结 4 862
夕颜
夕颜 2020-12-30 05:42

So according to the Zen of Python ... Explicit is better than implicit...Sparse is better than dense...Readability counts...but then agai

4条回答
  •  说谎
    说谎 (楼主)
    2020-12-30 06:14

    My wife Anna has nicknamed x[::-1] "the Martian Smiley" -- I mostly bow to her (and her long experience in training &c, and studies in human psychology &c), when it comes to judging what's easy and natural for most people, and she absolutely loves the martial smiley. "Just walk it backwards" -- how much more direct, and high-abstraction, than the detailed specification of "reverse it and then join it back"!

    Also, python -mtimeit is often a good judge of what's Pythonic: top Pythonistas, over the years, have of course tended to optimize what they most often needed and used, so a very substantial performance difference tells you what "goes with the grain" of the language and its top practitioners. And by that score, the martian smiley beats the detailed spec hands-down...:

    $ python -mtimeit '"".join(reversed("hello there!"))'
    100000 loops, best of 3: 4.06 usec per loop
    $ python -mtimeit '"hello there!"[::-1]'
    1000000 loops, best of 3: 0.392 usec per loop
    

    order-of-magnitude performance differences just don't leave that much room for doubt!-)

提交回复
热议问题