我遇到一个小问题:
例如,我们有字符串'YXY00'
。 'X'
的每个'Y'
可以分别替换为'Y'
或'X'
。在这个例子中,我们有2 ^ 3 = 8个替换选项,如:
YXY00
YXX00
YYY00
YYX00
XXY00
XXX00
XYY00
XYX00
如何使用Python 3.x获得此替换?
答案 0 :(得分:2)
您可以使用itertools.permutations()
来获取字符串的排列。然后通过应用一些替换逻辑,您可以得到以下结果:
import itertools
def permutate(source, changeset):
count = sum(1 for char in source if char in changeset)
holder = ''.join('{}' if char in changeset else char for char in source)
for perm in set(itertools.permutations(changeset * count, count)):
print(holder.format(*perm))
permutate('XY000Y00', 'XY')
结果:
XY000X00
XX000Y00
XY000Y00
XX000X00
YX000X00
YY000Y00
YX000Y00
YY000X00
答案 1 :(得分:1)
我重构了一些,现在它更具可读性:
def replace_at_index(string, index, replacement):
"""
Credit to: http://stackoverflow.com/users/95612/jochen-ritzel
>>> replace_at_index("abc", 1, "z")
'azc'
"""
return string[:index] + replacement + string[index + 1:]
def possible_replaces(string):
"""
>>> list(possible_replaces('YXY00'))
['XXY00', 'YXY00', 'YXY00', 'YYY00', 'YXX00', 'YXY00', 'YXY00', 'YXY00']
>>> list(possible_replaces('XYY000000'))
['XYY000000', 'YYY000000', 'XXY000000', 'XYY000000', 'XYX000000', 'XYY000000', 'XYY000000', 'XYY000000', 'XYY000000', 'XYY000000', 'XYY000000', 'XYY000000']
"""
for index, char in enumerate(string):
if char in 'XY':
yield replace_at_index(string, index, 'X')
yield replace_at_index(string, index, 'Y')
else:
yield string
我还写了一个更通用的解决方案:
def possible_replaces(string, to_multipy_replace = 'XY'):
"""
Returns a list of strings where each member of `to_multipy_replace` is replaced
by each member of said set.
>>> list(possible_replaces('YXY00'))
['XXY00', 'YXY00', 'YXY00', 'YYY00', 'YXX00', 'YXY00', 'YXY00', 'YXY00']
>>> list(possible_replaces('XYY0'))
['XYY0', 'YYY0', 'XXY0', 'XYY0', 'XYX0', 'XYY0', 'XYY0']
"""
for index, char in enumerate(string):
if char in to_multipy_replace:
for replacement in to_multipy_replace:
yield replace_at_index(string, index, replacement)
else:
yield string
您现在不仅限于'XY',而是任何令您满意的字符集。