defadd_string_with_plus(iters): s = "" for i inrange(iters): s += "xyz" assertlen(s) == 3*iters
defadd_bytes_with_plus(iters): s = b"" for i inrange(iters): s += b"xyz" assertlen(s) == 3*iters
defadd_string_with_format(iters): fs = "{}"*iters s = fs.format(*(["xyz"]*iters)) assertlen(s) == 3*iters
defadd_string_with_join(iters): l = [] for i inrange(iters): l.append("xyz") s = "".join(l) assertlen(s) == 3*iters
defconvert_list_to_string(l, iters): s = "".join(l) assertlen(s) == 3*iters
>>> timeit(add_string_with_plus(100000)) # 执行时间线性增加 100 loops, best of 3: 9.75 ms per loop >>> timeit(add_bytes_with_plus(100000)) # 二次增加 1000 loops, best of 3: 974 ms per loop >>> timeit(add_string_with_format(100000)) # 线性增加 100 loops, best of 3: 5.25 ms per loop >>> timeit(add_string_with_join(100000)) # 线性增加 100 loops, best of 3: 9.85 ms per loop >>> l = ["xyz"]*100000 >>> timeit(convert_list_to_string(l, 100000)) # 线性增加 1000 loops, best of 3: 723 µs per loop
Python的字符串操作是十分迅速的,在造数据的时候发现甚至比std::string还要好。
让生活更友好
彩蛋
1 2 3 4 5 6 7 8 9
import this
import antigravity
from __future__ import braces
from __future__ import barry_as_FLUFL >>> "Ruby" <> "Python" True
每一行都是一个彩蛋。
else 的妙用
1 2 3 4 5 6 7 8 9 10 11 12 13
defdoes_exists_num(l, to_find): for num in l: if num == to_find: print("Exists!") break else: print("Does not exist")
>>> some_list = [1, 2, 3, 4, 5] >>> does_exists_num(some_list, 4) Exists! >>> does_exists_num(some_list, -1) Does not exist