Skip to main content
 首页 » 编程设计

for循环长字符串中的Python字符串连接

2025年04月02日23mengfanrong

<分区>

我已经多次听说您不应该在 for 循环中进行字符串连接,因为字符串是不可变的,因此它会将连接计算为一个新的字符串实例,然后重新分配标识符。所以如果结果有 n 个字符,时间复杂度将是 O(n^2)

差: 在 O(n^2) 中运行。迭代“+”连接。

letters = "" 
for c in document: 
    if c.isalpha(): 
        letters += c 

好: 在 O(n) 中运行。迭代追加,最后一个“”.join()

document = "" 
temp = [] 
for c in document: 
    if c.isalpha():  
        temp.append(c) 
letters = "".join(temp) 

同时我也看到了

“一些后来的 Python 解释器实现已经开发出一种优化,允许这样的代码在线性时间内完成,..”

所以第一个解决方案也应该没问题?它是最新 python 构建中的优化吗?