与上一个问题相关:Python3 split() with generator。
我认为".split()“不是用正则表达式实现的。
我希望看到类似的东西,但不要在内存中创建完整的拆分列表,而是使用生成器或迭代器“即时”创建。
发布于 2012-05-26 04:17:30
这似乎比regex快一点:
def itersplit2(s, sep):
i = 0
l = len(sep)
j = s.find(sep, i)
while j > -1:
yield s[i:j]
i = j + l
j = s.find(sep, i)
else:
yield s[i:]但是比str.split慢10倍
发布于 2012-05-26 04:11:16
分隔符的版本不同于None:
def iter_split(s, sep):
start = 0
L = len(s)
lsep = len(sep)
assert lsep > 0
while start < L:
end = s.find(sep, start)
if end != -1:
yield s[start:end]
start = end + lsep
if start == L:
yield '' # sep found but nothing after
else:
yield s[start:] # the last element
start = L # to quit the loop我没有对它进行过严格的测试,所以它可能包含一些bug。将结果与str.split()进行了比较
sep = '<>'
s = '1<>2<>3'
print('--------------', repr(s), repr(sep))
print(s.split(sep))
print(list(iter_split(s, sep)))
s = '<>1<>2<>3<>'
print('--------------', repr(s), repr(sep))
print(s.split(sep))
print(list(iter_split(s, sep)))
sep = ' '
s = '1 2 3'
print('--------------', repr(s), repr(sep))
print(s.split(sep))
print(list(iter_split(s, sep)))
s = '1 2 3'
print('--------------', repr(s), repr(sep))
print(s.split(sep))
print(list(iter_split(s, sep)))它显示:
-------------- '1<>2<>3' '<>'
['1', '2', '3']
['1', '2', '3']
-------------- '<>1<>2<>3<>' '<>'
['', '1', '2', '3', '']
['', '1', '2', '3', '']
-------------- '1 2 3' ' '
['1', '2', '3']
['1', '2', '3']
-------------- '1 2 3' ' '
['1', '', '', '2', '', '', '3']
['1', '', '', '2', '', '', '3']默认None分隔符的实现会更复杂,因为有更多的规则。
无论如何,预编译的正则表达式是非常高效的。它们在编写它们时很容易出错,但一旦准备好,它们就会很快。
https://stackoverflow.com/questions/10759990
复制相似问题