3 回答
![?](http://img1.sycdn.imooc.com/54584cd10001404b02200220-100-100.jpg)
TA贡献1828条经验 获得超6个赞
如果你连接很多值,那么两者都没有。附加清单很昂贵。您可以使用StringIO。特别是如果你在很多操作中构建它。
from cStringIO import StringIO# python3: from io import StringIObuf = StringIO()buf.write('foo')buf.write('foo')buf.write('foo')buf.getvalue()# 'foofoofoo'
如果您已经从其他操作返回了完整列表,那么只需使用 ''.join(aList)
来自python FAQ:将多个字符串连接在一起的最有效方法是什么?
str和bytes对象是不可变的,因此将多个字符串连接在一起效率很低,因为每个连接都会创建一个新对象。在一般情况下,总运行时间成本是总字符串长度的二次方。
要累积许多str对象,推荐的习惯用法是将它们放入一个列表中并在结尾处调用str.join():
chunks = []for s in my_strings: chunks.append(s)result = ''.join(chunks)(另一个合理有效的习惯是使用io.StringIO)
要累积许多字节对象,推荐的习惯用法是使用就地连接(+ =运算符)扩展bytearray对象:
result = bytearray()for b in my_bytes_objects: result += b
编辑:我是愚蠢的,并将结果向后粘贴,使其看起来像是附加到列表比cStringIO更快。我还添加了对bytearray / str concat的测试,以及使用带有更大字符串的更大列表的第二轮测试。(python 2.7.3)
用于大型字符串列表的ipython测试示例
try:
from cStringIO import StringIO
except:
from io import StringIO
source = ['foo']*1000
%%timeit buf = StringIO()
for i in source:
buf.write(i)
final = buf.getvalue()
# 1000 loops, best of 3: 1.27 ms per loop
%%timeit out = []
for i in source:
out.append(i)
final = ''.join(out)
# 1000 loops, best of 3: 9.89 ms per loop
%%timeit out = bytearray()
for i in source:
out += i
# 10000 loops, best of 3: 98.5 µs per loop
%%timeit out = ""
for i in source:
out += i
# 10000 loops, best of 3: 161 µs per loop
## Repeat the tests with a larger list, containing
## strings that are bigger than the small string caching
## done by the Python
source = ['foo']*1000
# cStringIO
# 10 loops, best of 3: 19.2 ms per loop
# list append and join
# 100 loops, best of 3: 144 ms per loop
# bytearray() +=
# 100 loops, best of 3: 3.8 ms per loop
# str() +=
# 100 loops, best of 3: 5.11 ms per loop
添加回答
举报