【问题标题】:Generating all combinations of replaced strings生成替换字符串的所有组合
【发布时间】:2020-08-18 14:45:28
【问题描述】:

我有一个相当具体的编程问题已经困扰了我几个星期了,我相信这是正确的地方。

我需要一个函数,它可以生成各种子字符串的所有组合,例如,替换为更大的字符串;

thisfunction([['Hello','hi'],['Goodbye','bye'],['Hello','goodbye']], "This is a string that says Hello and Goodbye and Hello again")

应该返回

["String that says Hello, Goodbye and Hello again",
"String that says hi and Goodbye and Hello again",
"String that says hi and bye and Hello again",
"String that says Hello and bye and Hello again",
"String that says Hello, Goodbye and goodbye again",
"String that says hi and Goodbye and goodbye again",
"String that says hi and bye and goodbye again",
"String that says Hello and bye and goodbye again",]

我用正则表达式和替换函数尝试了各种策略,但没有成功
感谢所有想法!

【问题讨论】:

  • 您的列表['Hello','hi'],['Goodbye','bye'],['Hello','goodbye']] 包含'Hello' 两次;我是否正确地假设这意味着字符串中只有第一次出现的 Hello 应该被 hi 替换,并且只有第二个被 goodbye 替换?
  • @Błotosmętek 正确

标签: python string replace substring


【解决方案1】:

您可以使用itertools.productstr.format 来实现类似:

from itertools import product

def thisfunction(lst, s):
    for p in product(*lst):
        yield s.format(*p)

>>> list(thisfunction([['Hello','hi'],['Goodbye','bye'],['Hello','goodbye']], 
                      "This is a string that says {} and {} and {} again"))
['This is a string that says Hello and Goodbye and Hello again',
 'This is a string that says Hello and Goodbye and goodbye again',
 'This is a string that says Hello and bye and Hello again',
 'This is a string that says Hello and bye and goodbye again',
 'This is a string that says hi and Goodbye and Hello again',
 'This is a string that says hi and Goodbye and goodbye again',
 'This is a string that says hi and bye and Hello again',
 'This is a string that says hi and bye and goodbye again']

【讨论】:

  • 为了使其与 OP 的示例完全兼容,您可以在 s 中添加将每个子列表中的第一项替换为 {}
  • @Błotosmętek 是的。但是,这会使代码有点混乱,我认为 OP 应该在字符串中使用占位符。
  • 反正就是单线:for first, *rest in lst: s = s.replace(first, '{}')
  • @Błotosmętek,我不太明白我会把这行放在哪里,你能编辑上面的代码以反映它的外观吗,现在不用担心杂乱的代码:)跨度>
  • @Błotosmętek 不是真的。对于不会产生所需列表的初学者。此外,“Hello”是重复的,所以第二个列表将被忽略。
【解决方案2】:
from itertools import product

def thisfunction(lst, s):
    for first, *rest in lst:
        s = s.replace(first, '{}', 1)
    for p in product(*lst):
        yield s.format(*p)

print(list(thisfunction([['Hello','hi'],['Goodbye','bye'],['Hello','goodbye']], "This is a string that says Hello and Goodbye and Hello again")))

【讨论】:

  • 现在我明白了:D
  • 技术上更好的答案,@schwobaseggl 的修改版本我会支持但不接受
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-16
  • 2022-08-17
  • 2012-05-17
  • 1970-01-01
相关资源
最近更新 更多