栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python】选择正确的字符串累加姿势,速度可以提升数倍

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python】选择正确的字符串累加姿势,速度可以提升数倍

引言

在通读谷歌的 Python 代码规范文档中,发现了有意思的有一段话:

Avoid using the + and += operators to accumulate a string within a loop. In some conditions, accumulating a string with addition can lead to quadratic rather than linear running time. Although common accumulations of this sort may be optimized on CPython, that is an implementation detail. The conditions under which an optimization applies are not easy to predict and may change. Instead, add each substring to a list and ''.join the list after the loop terminates, or write each substring to an io.StringIO buffer. These techniques consistently have amortized-linear run time complexity.

大意就是说,避免在循环中使用 + 和 += 运算符累积字符串。替代的是,先将字符串放到一个列表 list 中,然后使用 ''.join(list) 的方法来累加字符串。或者你也可以使用 io.StringIO 缓冲。

这是因为在循环中使用 + 和 += 运算符累积字符串的时间复杂度是 O(n2),而使用 ''.join(list) 的时间复杂度是 O(n)。

方法 +/+=
>>> s = ''
>>> for i in ['a', 'b', 'c']:
...     s += i
... 
>>> s
'abc'
.join()
>>> s = ''.join(['a', 'b', 'c']) 
>>> s
'abc'
实验

这里设置一个实验对比 += 与 .join() 累加字符串耗时。

  • +=
import time
t1 = time.time()
s = ''
for i in [chr(i) for i in range(96, 123)]*1000000:
    s += i
t2 = time.time()
print(f'Time-consuming: {t2-t1}')
  • .join()
import time
t1 = time.time()
s = ''.join([chr(i) for i in range(96, 123)]*1000000)
t2 = time.time()
print(f'Time-consuming: {t2-t1}')

实验结果如下:

类型耗时
+=24.35s
''.join()0.26s

得出结论:当需要累加的字符串很多时,''.join() 的速度明显更快。

参考

https://google.github.io/styleguide/pyguide.html

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/878956.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号