Jean - 记录成长历程

  • 关于
  • Language
  • RSS Feed
  • 微博
  • 豆瓣
28
Dec

python技巧一则:某些情况下str.join比+=效率高

By admin|脚本编程|3 Comments

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))

无觅相关文章插件,快速提升流量

Tagged as: python
Add your comment →

3 Comments

  1. 尊敬的站长 您好 很喜欢你的博客风格 想和贵站交换链接

    网址 http://www.maikaolin-m18.cn

    标题 麦考林

    贵站链接已做好!

    [回复]

    admin 回复:
    01月 3rd, 2010 at 18:18

    @麦考林, 你好,你的站做的也很好,但是本站暂无和非技术性网站做链接的计划。

    [回复]

    By: 麦考林
    2010-01-03 at 11:12
  2. 额外资料

    连接与分割

    上面介绍序列类型时,我们已经使用了 + 号来做字符串的连接操作,在某些情况下这当然是不错的,然而在多数情况下我们其实都不推荐这种做法,因为大量的这种连接操作会大大影响效率。比如说这个例子:

    >>> ‘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!’

    [回复]

    By: admin Author
    2009-12-30 at 19:10

Leave your comment below! Cancel Reply

点击取消回复

View More Posts:
  • ←
  • →

分类

  • Linux系统 (61)
  • Linux集群 (4)
  • Web服务器 (26)
  • 创业相关 (6)
  • 工作笔记 (35)
  • 我爱折腾 (16)
  • 日记 (46)
  • 网络 (3)
  • 脚本编程 (49)

最新日志

  • 给Xcode增加git支持
  • 使用w3 total cache给wordpress提速
  • 从零开始,我的创业感悟
  • 为大众创造更美好的日常生活
  • 我的站立式工作平台

最新评论

  • admin on 关于
  • Caspar on 关于
  • admin on 关于
  • darkmi on 关于
  • darkmi on 我的站立式工作平台

博客互联

  • darkmi'blog
  • HackLog
  • leapsoul
  • Myredhat
  • Ninth element
  • Ti’blog
  • William Hua
  • young001
  • 左手键盘,右手书
  • 懒人运维
  • 曙光博客
  • 月夜
  • 月影
  • 杂货店一号铺
  • 王先进’s blog
  • 疯中舞步
  • 菜鸟的技术站
  • 运维进行时

技术

  • DBA BLOG
  • 回忆未来[张宴]
  • 扶凯
  • 王炜's Blog
  • 百变贝贝

Powered by the inLine Minimal WordPress Theme