【发布时间】:2013-05-27 21:57:09
【问题描述】:
今天我试图找到一种方法,在 python 中对字符串进行一些处理。据说比我更高级的程序员不要使用+=,而是使用''.join(),我也可以在例如:http://wiki.python.org/moin/PythonSpeed/#Use_the_best_algorithms_and_fastest_tools 中阅读此内容。
但是我自己对此进行了测试,并发现了一些奇怪的结果(这并不是我试图猜测它们,而是我想了解)。
这个想法是如果有一个包含空格的字符串"This is \"an example text\",则该字符串应转换为Thisis"an example text"containingspaces 空格被删除,但仅在引号之外。
我测量了两种不同版本的算法的性能,一种使用''.join(list),另一种使用+=
import time
#uses '+=' operator
def strip_spaces ( s ):
ret_val = ""
quote_found = False
for i in s:
if i == '"':
quote_found = not quote_found
if i == ' ' and quote_found == True:
ret_val += i
if i != ' ':
ret_val += i
return ret_val
#uses "".join ()
def strip_spaces_join ( s ):
#ret_val = ""
ret_val = []
quote_found = False
for i in s:
if i == '"':
quote_found = not quote_found
if i == ' ' and quote_found == True:
#ret_val = ''.join( (ret_val, i) )
ret_val.append(i)
if i != ' ':
#ret_val = ''.join( (ret_val,i) )
ret_val.append(i)
return ''.join(ret_val)
def time_function ( function, data):
time1 = time.time();
function(data)
time2 = time.time()
print "it took about {0} seconds".format(time2-time1)
在我的机器上,这产生了这个输出,对于使用 += 的算法有一点优势
print '#using += yields ', timeit.timeit('f(string)', 'from __main__ import string, strip_spaces as f', number=1000)
print '#using \'\'.join() yields ', timeit.timeit('f(string)', 'from __main__ import string, strip_spaces_join as f', number=1000)
当使用 timeit 计时:
#using += yields 0.0130770206451
#using ''.join() yields 0.0108470916748
差别真的很小。但是为什么 ''.join() 没有明确执行使用 += 的功能,但 ''.join() 版本似乎有一个小优势。
我在 Ubuntu 12.04 上使用 python-2.7.3 对此进行了测试
【问题讨论】:
-
在测试时序时,使用
timeit模块。 -
对于大于约 400 个字符的字符串,使用带有
join的列表更快。 -
@Blender 字符串的长度最终为 43000000,还是我误解了你?
-
您在这里也没有真正比较相同的东西。您正在比较多个
+=与多个appends,然后是单个''.join()。 -
我觉得我应该提一下:这不仅仅与性能有关。可读性也很重要(以及能够调试和推理代码),
.join每次都在这里获胜。
标签: python performance list-comprehension augmented-assignment