string replace in Python 2.7
使用python 2.7并处理下面的字符串替换问题,想知道在算法空间复杂性和算法时间复杂性方面是否有更好的想法?
我创建了一个额外的列表来表示结果,因为字符串python 2.7是不可变的,我还创建了一个额外的字典来加速字符替换表的查找。
在本例中,from:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | ''' Given"data","from", and"to" fields, replaces all occurrences of the characters in the"from" field in the"data" field, with their counterparts in the"to" field. Example: Input: Data:"Hello World" From:"lod" To:"xpf" Output: "Hexxp Wprxf" ''' from collections import defaultdict def map_strings(from_field, to_field, data): char_map = defaultdict(str) result = [] for i,v in enumerate(from_field): char_map[v]=to_field[i] for v in data: if v not in char_map: result.append(v) else: result.append(char_map[v]) return ''.join(result) if __name__ =="__main__": print map_strings('lod', 'xpf', 'Hexxp Wprxf') |
标准模块中有有效的机械装置。首先使用
1 2 3 4 | import string trans = string.maketrans('lod', 'xpf') print"Hello World".translate(trans) |
输出
1 | Hexxp Wprxf |
但是,如果您想手动执行,这里有一种方法比您当前的代码更有效:
1 2 3 4 5 6 | def map_strings(from_field, to_field, data): char_map = dict(zip(from_field, to_field)) return ''.join([char_map.get(c, c) for c in data]) s = map_strings('lod', 'xpf', 'Hello World') print s |
注意,在python 3中,
您也可以使用
1 2 3 4 | def map_strings(from_field, to_field, data): for f, t in zip(from_field, to_field): data = data.replace(f, t) return data |