在python中反转字符串的最快方法 [英] Fastest way to reverse a string in python

查看:34
本文介绍了在python中反转字符串的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想出了两种不同的方法来反转 Python 中的字符串.

I was able to come up with two different ways to reverse a string in Python.

常识表明,代码行数越多,运行速度就越慢.

Commonsense dictates that the more lines of code the slower it runs.

我做了以下几行代码:

代码1

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

代码 2

st[::-1]

这些提供了类似的性能.对于一个 20000 长的字符串,我什至看不到性能上的差异.

These give similar performance. For a 20000 long string I am not able to see a difference of even a millisecond in performance.

我认为第一个应该是一种较慢的方法,因为它执行的操作多 3 倍.

I think the first one should be a slower approach because it performs 3x more operations.

问题

为什么我没有看到性能差异?

Why am I not seeing a performance difference?

推荐答案

我看到了不同之处.

首先,map(lambda x: x, st) 是怎么回事?目的是什么?

First of all, what is up with map(lambda x: x, st)? What is the purpose?

使用 timeit 模块来测试您的代码:

Use the timeit module to test your code:

$ 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

如您所见,对于此特定输入,切片在我的机器上快了约 8 倍.也更简洁.

As you can see, the slice is ~8x faster on my machine for this particular input. It's also more concise.

这篇关于在python中反转字符串的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆