我得到了这样一句话:kfc
然后是字典:{'k':'1', 'c':'3'}
我怎样才能得到这样的清单?
kfc, 1fc, kf3, 1f3
这意味着总有2^n
种可能性,n
是该词中词典键的数量。
P / s:我只能想到使用递归函数,但是,我更喜欢非递归函数。
答案 0 :(得分:2)
您可以使用itertools.product
。例如,让我们定义预备词:
>>> import itertools
>>> s = 'kfc'
>>> d = {'k':'1', 'c':'3'}
现在,让我们计算结果:
>>> [ ''.join(x) for x in itertools.product( *[(c, d.get(c)) if d.get(c) else c for c in s] ) ]
['kfc', 'kf3', '1fc', '1f3']
首先,我们使用列表理解来获得我们需要考虑的可能性:
>>> [(c, d.get(c)) if d.get(c) else c for c in s]
[('k', '1'), 'f', ('c', '3')]
在上面的列表理解中,我们遍历字符串c
中的每个字符s
。对于每个c
,如果不存在(c, d[c])
,我们会收集d[c]
的可能性,如果不存在,则只收集c
。
接下来,我们使用itertools创建所有可能的产品:
>>> list( itertools.product( *[(c, d.get(c)) if d.get(c) else c for c in s] ) )
[('k', 'f', 'c'), ('k', 'f', '3'), ('1', 'f', 'c'), ('1', 'f', '3')]
上面有我们需要的答案。我们只需要使用''.join
重新组合字符串:
>>> [ ''.join(x) for x in itertools.product( *[(c, d.get(c)) if d.get(c) else c for c in s] ) ]
['kfc', 'kf3', '1fc', '1f3']