说我有一个看起来像
的字符串'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
答案 0 :(得分:5)
单行,s
为'one, two, three,'
:
>>> [s[:i] + "." + s[i+1:] for i in range(len(s)) if s[i] == ","]
['one. two, three,', 'one, two. three,', 'one, two, three.']
或者,将最外面的[ ]
替换为( )
,以改为生成对象。
当然,这仅适用于单字符替换。为了更一般地用其他字符串替换子字符串,您应该使用其他解决方案之一,例如,使用正则表达式。
答案 1 :(得分:4)
您可以使用枚举:
["%s.%s" % (s[:i], s[i+1:]) for i, c in enumerate(s) if c == ","]
或正则表达式:
["%s.%s" % (s[:m.start()], s[m.start()+1:]) for m in re.finditer(',', s)]
答案 2 :(得分:4)
我能找到的简单:
import re
s = 'one, two, three,'
# delim will be used as a regex
delim = ','
[s[:i.start()] + "." + s[i.end():] for i in re.finditer(delim, s)]
答案 3 :(得分:2)
import itertools
l_string = "one, two, three,".rstrip(',').split(',')
separators = lambda pos: [ '.' if i==pos else ',' for i,x in enumerate(l_string) ]
print [ "".join([ "".join(elem) for elem in itertools.izip( l_string, separators(pos) ) ]) for pos in range(len(l_string)) ]
>>> ['one. two, three,', 'one, two. three,', 'one, two, three.']