简体   繁体   English

在python中反转字符串的最快方法

[英]Fastest way to reverse a string in python

I was able to come up with two different ways to reverse a string in Python.我能够想出两种不同的方法来反转 Python 中的字符串。

Commonsense dictates that the more lines of code the slower it runs.常识表明,代码行数越多,运行速度就越慢。

I made the following lines of code:我做了以下几行代码:

Code1代码1

"".join(reversed(map(lambda x:x,st)))

Code2代码2

st[::-1]

These give similar performance.这些提供了类似的性能。 For a 20000 long string I am not able to see a difference of even a millisecond in performance.对于 20000 长的字符串,我什至看不到性能上的差异。

I think the first one should be a slower approach because it performs 3x more operations.我认为第一个应该是一种较慢的方法,因为它执行 3 倍多的操作。

Question问题

Why am I not seeing a performance difference?为什么我没有看到性能差异?

I see a difference.我看到了不同。

First of all, what is up with map(lambda x: x, st) ?首先, map(lambda x: x, st)怎么回事? What is the purpose?目的是什么?

Use the timeit module to test your code:使用timeit模块测试您的代码:

$ python -m timeit '"".join(reversed("abcdefghijklmnopqrstuvwxyz"))'
1000000 loops, best of 3: 0.586 usec per loop
$ python -m timeit '"abcdefghijklmnopqrstuvwxyz"[::-1]'           
10000000 loops, best of 3: 0.0715 usec per loop

As you can see, the slice is ~8x faster on my machine for this particular input.正如您所看到的,对于这个特定的输入,切片在我的机器上快了大约 8 倍。 It's also more concise.它也更简洁。

s=input("enter string")
print(s[::-1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM