O(n)解决方案:
reps = {'1/2': 'half', '1/4': 'quarter', '3/4': 'three quarters'}
li = ['I own 1/2 bottle', 'Give me 3/4 of the profit']
map(lambda s: ' '.join([reps.get(w,w) for w in s.split()]),li)
Out[6]: ['I own half bottle', 'Give me three quarters of the profit']
#for those who don't like `map`, the list comp version:
[' '.join([reps.get(w,w) for w in sentence.split()]) for sentence in li]
Out[9]: ['I own half bottle', 'Give me three quarters of the profit']
在循环中进行大量替换调用的问题在于它使您的算法成为O(n ** 2).当你有一个长度为3的替换字典时没什么大不了的,但是当它变大时,突然你有一个非常慢的算法,不需要.
正如评论中所指出的,这种方法从根本上取决于能够基于空格进行标记化 – 因此,如果您的替换键中有任何空格(比如说,您想要替换一系列单词),这种方法将无效.然而,能够替换单词是一种比需要替换词组更频繁的操作,所以我不同意那些认为这种方法不够通用的评论者.