28
Dec
python技巧一则:某些情况下str.join比+=效率高
If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s = s + t or s += t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.
文中的s和t是什么?
There are six sequence types: strings, Unicode strings, lists, tuples, buffers, and xrange objects.
For other containers see the built in dict and set classes, and the collections module.
代码片段。不言自明。
for root, dirs, files in os.walk('/media/cdrom0'): export+="\n %s;%s;%s" % (root,dirs,files) open('TokyoHot1', 'w').write(export)
for root, dirs, files in os.walk('/media/cdrom0'): export.append("\n %s;%s;%s" % (root,dirs,files)) open('TokyoHot2', 'w').write(''.join(export))
尊敬的站长 您好 很喜欢你的博客风格 想和贵站交换链接
网址 http://www.maikaolin-m18.cn
标题 麦考林
贵站链接已做好!
[回复]
admin 回复:
01月 3rd, 2010 at 18:18
@麦考林, 你好,你的站做的也很好,但是本站暂无和非技术性网站做链接的计划。
[回复]
额外资料
连接与分割
上面介绍序列类型时,我们已经使用了 + 号来做字符串的连接操作,在某些情况下这当然是不错的,然而在多数情况下我们其实都不推荐这种做法,因为大量的这种连接操作会大大影响效率。比如说这个例子:
>>> ‘I ‘+’love ‘+’python!’
‘I love python!’
分解开来看就是 (‘I ‘+’love ‘) + ‘python!’ ,第一次连接操作就会产生一个中间对象 ‘I love ‘ ,而这个对象从结果来看完全是没有用的。大量的连接操作,就会产生大量无用的中间对象。浪费了分配内存所花费的时间也浪费了内存。
所以,两个字符串的连接用 + 是很方便的,不过两个以上的字符串连接我们还是更推荐下面这个方法:
>>> ‘ ‘.join(['I', 'love', 'python!'])
‘I love python!’
你还可以用其他字符串来进行连接:
>>> ‘–’.join(['I', 'love', 'python!'])
‘I–love–python!’
[回复]