假设我有一个看起来像的字符串
'one, two, three,'
什么是通过用“。”替换“,”进行迭代的pythonic方式 一次一个?理想情况下,函数的返回值如下所示:
['one. two, three,' , 'one, two. three,' , 'one, two, three.']
选择答案的推理,感谢您的贡献!
import timeit
def one(s):
b = ["%s.%s" % (s[:i], s[i+1:]) for i, c in enumerate(s) if c == ","]
def two(s):
b = [s[:i] + "." + s[i+1:] for i in range(len(s)) if s[i] == ","]
def thr(s):
b = [s[:i] + "." + s[i+1:] for i, c in enumerate(s) if s[i] == ","]
def fou(s):
ss = s.split(',')
b = [','.join(ss[:i]) + '.' + ','.join(ss[i:]) for i in range(1,len(ss))]
a = 'one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,'
print(timeit.timeit('one(a)', 'from __main__ import one, a', number = 1000000))
print(timeit.timeit('two(a)', 'from __main__ import two, a', number = 1000000))
print(timeit.timeit('thr(a)', 'from __main__ import thr, a', number = 1000000))
print(timeit.timeit('fou(a)', 'from __main__ import fou, a', number = 1000000))
# C:\dev\goddangit>python timin.py
# 14.3008527857
# 11.8759967856
# 13.3739626708
# 18.8536401851