字符串替换组合 [英] String Replacement Combinations
问题描述
所以我有一个字符串 1xxx1,我想用一个字符替换某个数字(也许全都不是),比如说 5。我想要该字符串的所有可能组合(...也许是排列),其中x可以替换为x或保留为x。我希望将这些结果存储在列表中。
So I have a string '1xxx1' and I want to replace a certain number (maybe all maybe none) of x's with a character, let's say '5'. I want all possible combinations (...maybe permutations) of the string where x is either substituted or left as x. I would like those results stored in a list.
所以所需的结果将是
>>> myList = GenerateCombinations('1xxx1', '5')
>>> print myList
['1xxx1','15xx1','155x1','15551','1x5x1','1x551','1xx51']
很显然,我希望它能够处理任意长度的带有任意数量x的字符串以及能够替换任意数字的字符串。我尝试使用循环和递归来解决这个问题,但毫无用处。任何帮助将不胜感激。
Obviously I'd like it to be able to handle strings of any length with any amount of x's as well as being able to substitute any number. I've tried using loops and recursion to figure this out to no avail. Any help would be appreciated.
推荐答案
如何:
from itertools import product
def 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
。)
基本上,首先,我们为源词中的每个字母列出每个可能的目标:
(Note that you seem to be missing 15x51
.)
Basically, first we make a list of every possible target for each letter in the source word:
>>> 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
来获得这些可能性的笛卡尔积并将结果合并在一起。
And then we use itertools.product
to get the Cartesian product of these possibilities and join the results together.
奖金点,修改以接受替换字典。 :^)
For bonus points, modify to accept a dictionary of replacements. :^)
这篇关于字符串替换组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!