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

时间:2015-08-07 13:51:32

标签: python string list split character

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

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

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

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

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

知道我怎么能这样做吗?

2 个答案:

答案 0 :(得分:2)

这可以吗?

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)

答案 1 :(得分:0)

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])
)