次のような文字列があるとします
'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