Python 基于预定义字符串和字典生成不同的字符串组合
我正在尝试编写一个函数,它将根据预定义的字典提供给定字符串的所有可能组合。假设这样一个例子:Python 基于预定义字符串和字典生成不同的字符串组合,python,string,dictionary,combinations,Python,String,Dictionary,Combinations,我正在尝试编写一个函数,它将根据预定义的字典提供给定字符串的所有可能组合。假设这样一个例子: dict = {'a':'á', 'a':'ä', 'y':'ý'} string = "antony" word_combination(string, dict) #desired function 预期结果应该是: ["antony", "ántony", "äntony", "ántoný",
dict = {'a':'á', 'a':'ä', 'y':'ý'}
string = "antony"
word_combination(string, dict) #desired function
预期结果应该是:
["antony", "ántony", "äntony", "ántoný", "äntoný", "antoný"]
i、 e.我们创建了所有可能的已定义字符串组合,并根据已定义的字典进行替换。
有什么建议/提示吗?在将您的词典转换为有效词典后,这里有一个解决方案:
import itertools
d = {'a':['á','ä'], 'y':['ý']}
string = "Anthony"
# if since each char can be replaced with itself, add it to the list of
# potential replacements.
for k in d.keys():
if k not in d[k]:
d[k].append(k)
res = []
for comb in [zip(d.keys(), c) for c in itertools.product(*d.values())]:
s = string
for replacements in comb:
s = s.replace(*replacements)
res.append(s)
结果是:
['ánthoný', 'ánthony', 'änthoný', 'änthony', 'anthoný', 'anthony']
您的dict无效,dict不能有重复的密钥。非常感谢!只是为了完整性:对于comb中的替换,应交换“在正确的解决方案行中:”和“s=string”。Oops。我的错。谢谢更新了解决方案。