很想知道人们是否可以比我的实现更快(使用纯Python,或者其他什么,但只是为了你)。
sentence = "This is some example sentence where we remove parts"
matches = [(5, 10), (13, 18), (22, 27), (38, 42)]
目标是在这些范围内删除。例如。在匹配 (5, 10) 的返回值中应省略索引 (5, 6, 7, 8, 9) 处的字符。
我的实现:
def remove_matches(sentence, matches):
new_s = ''
lbound = 0
for l, h in matches:
news += sentence[lbound:l]
lbound = h
new_s += sentence[matches[-1][1]:]
return new_s
结果:'This me le sce where weove parts'
请注意,匹配永远不会重叠,您可以利用这一事实。
实际上,我的主要问题很简单:我们不能以某种矢量化的方式做到这一点吗?我确信 numpy 可以,但我怀疑在这种情况下这会更有效。
基准:
PascalvKooten: 1000000 loops, best of 3: 1.34 µs per loop
Ted Klein Bergman (1): 1000000 loops, best of 3: 1.59 µs per loop
Ted Klein Bergman (2): 100000 loops, best of 3: 2.58 µs per loop
Prune: 100000 loops, best of 3: 2.05 µs per loop
njzk2: 100000 loops, best of 3: 3.19 µs per loop
最佳答案
这可能会更快。这基本上是您的解决方案,但使用列表而不是字符串。由于列表是可变的并且不需要每个循环都创建,所以它应该会快很多(尽管可能不是对于这么少的匹配)。
sentence = "This is some example sentence where we remove parts"
matches = [(5, 10), (13, 18), (22, 27), (38, 42)]
def remove_matches(sentence, matches):
result = []
i = 0
for x, y in matches:
result.append(sentence[i:x])
i = y
result.append(sentence[i:])
return "".join(result)
否则此方法可能会更快:
def remove_matches(sentence, matches):
return "".join(
[sentence[0:matches[i][0]] if i == 0 else
sentence[matches[i - 1][1]:matches[i][0]] if i != len(matches) else
sentence[matches[i - 1][1]::] for i in range(len(matches) + 1)
])
关于python - 从字符串中删除范围内的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38709711/