小编uma*_*a66的帖子

将串联字符串分配给python中的变量时,为什么这么慢?

如果仅是如下所示的字符串串联,则立即完成。

test_str = "abcdefghijklmn123456789"
str1 = ""
str2 = ""

start = time.time()
for i in range(1, 100001):

    str1 = str1 + test_str
    str2 = str2 + test_str

    if i % 20000 == 0:
        print("time(sec) => {}".format(time.time() - start))
        start = time.time()
Run Code Online (Sandbox Code Playgroud)

恒定的处理时间

time(sec) => 0.013324975967407227
time(sec) => 0.020363807678222656
time(sec) => 0.009979963302612305
time(sec) => 0.01744699478149414
time(sec) => 0.0227658748626709
Run Code Online (Sandbox Code Playgroud)

莫名其妙地,将串联字符串分配给另一个变量会使过程变得越来越慢。

test_str = "abcdefghijklmn123456789"
str1 = ""
str2 = ""

start = time.time()
for i in range(1, 100001):

    str1 = str1 + …
Run Code Online (Sandbox Code Playgroud)

python big-o append string-concatenation

15
推荐指数
1
解决办法
592
查看次数

标签 统计

append ×1

big-o ×1

python ×1

string-concatenation ×1