用列表中的每个其他字母替换字符串中的某些字母

Replacing certain letters in a string by every other letter in a list

我有两个列表:一个是字符串列表,另一个是单个字符串列表:

basis = ['ssaa','asas']
sample = ['x','y','z']

我希望我的程序用示例列表中的 every 元素替换基础中的 every 's' 字符。所以结果应该是这样的:

result = ['xxaa','xyaa','xzaa','yxaa','yyaa','yzaa','zxaa','zyaa','zzaa','axax','axay','axaz'...]

所以结果包含所有可能的组合。

知道我该怎么做吗?

这样可以吗?

from itertools import product

basis = ['ssaa','asas']
sample = ['x','y','z']

results = []
for base in basis:
    for comb in map(list, product(sample, repeat=base.count('s'))):
        results.append(''.join(comb.pop(0) if l == 's' else l for l in base))
print(results)
from itertools import chain, product

basis = ['ssaa', 'asas']
sample = ['x', 'y', 'z']

result = list(chain(*[
    map(lambda c: ''.join(c),
        product(*[sample if b == 's' else b for b in bb])
    ) for bb in basis
]))

这段代码可以重复使用(简化)以在 Hangman 游戏中生成所有可能的单词:)

from itertools import chain, product
import string

current = '_a_e' # game? fame? lame? ;)
letters = list(string.ascii_lowercase)

words = map(
    lambda c: ''.join(c),
    product(*[letters if x == '_' else x for x in current])
)