gpt4 book ai didi

python - 如何在python中替换多个字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 07:55:33 26 4
gpt4 key购买 nike

我正在尝试替换列表中的多个字符串,但我做不到。我要替换的字符串是。数字代表单词的正确顺序

sentence = ['1', '2', '3', '4']

我想用文本“i”、“put”、“this”、“here”替换数字,如下所示

['i', 'put', 'this', 'here']

我找到了一行代码,它只替换了一个单词。

newsentence = [n.replace('1', 'I') for n in sentence]

我尝试将代码重复 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]

但结果是最后一次替换被执行导致

['1', '2', '3', 'here']

感谢任何反馈

最佳答案

请参阅answer @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']

这很好,但是如果您决定在尚未定义输出的 mapping 处投入更多输入,您将收到 KeyError。要轻松处理此问题,您可以使用 dict.get ,它允许您提供在给定键丢失时返回的回退值。

newsentence = [mapping.get(word, word) for word in sentence]
# ['I', 'put', 'this', 'here']

A good reference on dict.get.


在这种情况下,不仅基于映射的解决方案更高效(请参阅@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]

但是,在基于映射的解决方案中,它们是分开的

# DATA
mapping = {
'1': 'i',
'2': 'put',
'3': 'this',
'4': 'here',
}

# LOGIC
newsentence = [mapping.get(word, word) for word in sentence]

这给你带来了什么?假设你最终不得不支持映射 1000 个单词,并且这些单词经常变化。将这些词与逻辑混合在一起使得它们更难找到,并且如果更改只会影响数据或者也可能意外更改控制流,则更难以在精神上解耦。使用基于映射的解决方案,可以肯定的是,更改只会影响数据。

考虑到我们需要添加一个 '1a''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]

糟糕!在基于映射的示例中,这种类型的错误在设计上是不可能的。

此外,通过将数据与逻辑分离,可以开始将数据存储在单独的文件(例如 JSON 或 YAML)中。这使得版本控制更加直接。然后它打开了拥有用户可自定义映射的可能性,您不必将这些映射硬编码到脚本中。解耦 == 好。

关于python - 如何在python中替换多个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49465391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com