字符串替换组合

字符串替换组合,第1张

字符串替换组合

怎么样:

from itertools import productdef filler(word, from_char, to_char):    options = [(c,) if c != from_char else (from_char, to_char) for c in word]    return (''.join(o) for o in product(*options))

这使

>>> filler("1xxx1", "x", "5")<generator object <genexpr> at 0x8fa798c>>>> list(filler("1xxx1", "x", "5"))['1xxx1', '1xx51', '1x5x1', '1x551', '15xx1', '15x51', '155x1', '15551']

(请注意,您似乎丢失了

15x51
。)基本上,首先,我们为源单词中的每个字母列出每个可能的目标:

>>> word = '1xxx1'>>> from_char = 'x'>>> to_char = '5'>>> [(c,) if c != from_char else (from_char, to_char) for c in word][('1',), ('x', '5'), ('x', '5'), ('x', '5'), ('1',)]

然后,我们使用

itertools.product
这些可能性的笛卡尔积,并将结果结合在一起。

对于奖励积分,进行修改以接受替换字典。:^)



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5648343.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存