我正在尝试替换列表中的多个字符串,但我做不到。我要替换的字符串是。数字代表单词的正确顺序
sentence = ['1', '2', '3', '4']
Run Code Online (Sandbox Code Playgroud)
我想用文本“i”、“put”、“this”、“here”替换数字,如下所示
['i', 'put', 'this', 'here']
Run Code Online (Sandbox Code Playgroud)
我发现一行代码只能替换一个单词。
newsentence = [n.replace('1', 'I') for n in sentence]
Run Code Online (Sandbox Code Playgroud)
我尝试重复该代码 4 次,以便它替换所有数字。
newsentence = [n.replace('1', 'I') for n in sentence]
newsentence = [n.replace('2', 'put') for n in sentence]
newsentence = [n.replace('3', 'this') for n in sentence]
newsentence = [n.replace('4', 'here') for n in sentence]
Run Code Online (Sandbox Code Playgroud)
但结果是执行了最后一次替换,导致
['1', '2', '3', 'here']
Run Code Online (Sandbox Code Playgroud)
感谢您的任何反馈
请参阅@KeyurPotdar 的答案,以获取原始解决方案不起作用的原因的解释。
对于您的问题的基于列表理解的解决方案(看起来您正在追求),您可以创建输入到输出的映射,然后使用您的输入迭代该映射
mapping = {
'1': 'i',
'2': 'put',
'3': 'this',
'4': 'here',
}
sentence = ['1', '2', '3', '4']
newsentence = [mapping[word] for word in sentence]
# ['I', 'put', 'this', 'here']
Run Code Online (Sandbox Code Playgroud)
这很好,但是如果您决定抛出更多mapping尚未定义输出的输入,您将得到一个KeyError. 为了轻松处理这个问题,您可以使用dict.get,它允许您提供一个在给定键丢失时返回的后备值。
newsentence = [mapping.get(word, word) for word in sentence]
# ['I', 'put', 'this', 'here']
Run Code Online (Sandbox Code Playgroud)
在这种情况下,基于映射的解决方案不仅更高效(请参阅@KeyurPotdar 的注释),而且将代码分离为数据和逻辑也是正确的做法™。
如果您可以将问题从基于代码/逻辑(例如原始问题中的列表推导式的序列)转换为基于映射,您几乎总是会在可维护性和代码清晰度方面获胜。观察这个解决方案,数据和逻辑都是混合的:
newsentence = [n.replace('1', 'I') for n in sentence]
newsentence = [n.replace('2', 'put') for n in newsentence]
newsentence = [n.replace('3', 'this') for n in newsentence]
newsentence = [n.replace('4', 'here') for n in newsentence]
Run Code Online (Sandbox Code Playgroud)
然而,在基于映射的解决方案中,它们是分开的
# DATA
mapping = {
'1': 'i',
'2': 'put',
'3': 'this',
'4': 'here',
}
# LOGIC
newsentence = [mapping.get(word, word) for word in sentence]
Run Code Online (Sandbox Code Playgroud)
这给你买了什么?假设您最终必须支持映射 1000 个单词,并且这些单词经常变化。将单词与逻辑混合在一起会使它们更难找到,并且如果更改只会影响数据或者也可能意外更改控制流,则更难以在精神上解耦。对于基于映射的解决方案,可以肯定的是,更改只会影响数据。
'1a'考虑一下我们需要添加to的映射'we'。在混合逻辑/数据示例中,很容易错过更改sentence为newsentence:
newsentence = [n.replace('1', 'I') for n in sentence]
newsentence = [n.replace('1a', 'we') for n in sentence]
newsentence = [n.replace('2', 'put') for n in newsentence]
newsentence = [n.replace('3', 'this') for n in newsentence]
newsentence = [n.replace('4', 'here') for n in newsentence]
Run Code Online (Sandbox Code Playgroud)
哎呀!在基于映射的示例中,这种类型的错误在设计上是不可能出现的。
此外,通过将数据与逻辑解耦,我们可以开始将数据存储在单独的文件中(例如 JSON 或 YAML)。这使得版本控制更加简单。然后,它提供了获得用户可自定义映射的可能性,您不必将这些映射硬编码到脚本中。解耦==好。