【摘】人生苦短,每日python

python和它的字符串拼接

不懂效率的人,会这样拼接

>>> s = ''
>>> for substring in ['hello ', 'world ']:
...  s += substring
...
>>> print(s)
hello world

python字符串是不可变的,拼接任意不可变序列都会生成一个新的序列对象。
即是说,每拼接一次,就要重新分配个空间,所以效率极低。

考虑效率的人,会这样拼接

>>> s = ''.join(['hello ', 'world '])
>>>
>>> print(s)
hello world

join()的速度很快,但是可读性很差。

中庸的人,会这样拼接

>>> s = '%s%s' % ('hello ', 'world ')
>>>
>>> print(s)
hello world

已知字符串的数目,代码的性能也不是很重要,或者优化字符串拼接节省的开销很小时,可以试试format或%。


python和它的枚举enumerate

不会用枚举的人,写这样的代码:

>>> i = 0
>>> for e in ['one', 'two', 'three']:
...     print(i, e)
...     i += 1
...
(0, 'one')
(1, 'two')
(2, 'three')

会用枚举的人,写这样的代码:

>>> for i, e in enumerate(['one', 'two', 'three']):
...     print(i,e)
...
(0, 'one')
(1, 'two')
(2, 'three')

摘自 《Python高级编程》

猜你喜欢

转载自www.cnblogs.com/featherw/p/10300617.html