使用Python 2.7并在下面的字符串替换问题上工作,想知道在算法空间复杂度和算法时间复杂度方面是否有更好的想法?Python中的字符串替换2.7
我创建了一个额外的列表来表示结果,因为字符串Python 2.7是不可变的,我还创建了一个额外的字典来加速字符替换表的查找。
在该示例中,From:"lod"
和To:"xpf"
表示遇到l
时,替换为x
;当遇到o
时,替换为p
;当遇到d
时,请替换为f
。
'''
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')
[str.maketrans(https://docs.python.org/3/library/stdtypes.html#str.maketrans) – wwii
@wwii注意的问题被标记为'python-2.7'; 'str.maketrans'方法只在Python 3中存在,尽管Python 2与'string.maketrans'函数略有不同,正如我在答案中提到的那样。 –
@ PM2Ring,aye'''string.maketrans'''是。 – wwii