Python 如何用所有可能的组合替换字典列表中的字符串

Python 如何用所有可能的组合替换字典列表中的字符串,python,list,Python,List,我想用名为gRep1Map的字典替换lst中列出的名为test1的字符串。它需要使用gRep1Map中的字符返回所有可能的组合。我得到一个输出,但不是我想要的。似乎真的找不到实现这一目标的方法 这是我的密码 text = "Test1" #Create dictionary gReplMap = { 'a': '@', 'e': '3', 'i': '1', 'o': '0', 't': '+', 'A': '@', 'E': '3', 'I':

我想用名为
gRep1Map
的字典替换lst中列出的名为
test1
的字符串。它需要使用
gRep1Map
中的字符返回所有可能的组合。我得到一个输出,但不是我想要的。似乎真的找不到实现这一目标的方法

这是我的密码

text = "Test1"

#Create dictionary
gReplMap = { 'a': '@', 'e': '3', 'i': '1', 'o': '0', 't': '+',
             'A': '@', 'E': '3', 'I': '1', 'O': '0', 'T': '+',
}

lst = []

for old, new in gReplMap.items():
    text = text.replace(old, new)
    lst.append(text)
    print(lst)
输出如下所示

['Test1']
['Test1', 'T3st1']
['Test1', 'T3st1', 'T3st1']
['Test1', 'T3st1', 'T3st1', 'T3st1']
['Test1', 'T3st1', 'T3st1', 'T3st1', 'T3s+1']
['Test1', 'T3st1', 'T3st1', 'T3st1', 'T3s+1', 'T3s+1']
['Test1', 'T3st1', 'T3st1', 'T3st1', 'T3s+1', 'T3s+1', 'T3s+1']
['Test1', 'T3st1', 'T3st1', 'T3st1', 'T3s+1', 'T3s+1', 'T3s+1', 'T3s+1']
['Test1', 'T3st1', 'T3st1', 'T3st1', 'T3s+1', 'T3s+1', 'T3s+1', 'T3s+1', 'T3s+1']
['Test1', 'T3st1', 'T3st1', 'T3st1', 'T3s+1', 'T3s+1', 'T3s+1', 'T3s+1', 'T3s+1', '+3s+1']
但我希望它是这样的

['test1', 'tes+1', 't3st1', 't3s+1', '+est1', '+es+1', '+3st1', '+3s+1']
有人能帮忙吗?

(减少
的有用性是罕见的案例)

来自itertools导入组合的

从functools导入reduce
out={
reduce(lambda x,y:x.replace(y[0],y[1]),repls,text)
对于范围内的n(len(gReplMap)+1)
对于组合中的repl(gReplMap.items(),n)
}
产生:

>>输出
{'+3s+1','+3st1','+es+1','+est1','T3s+1','T3st1','Tes+1','Test1'}
如果您希望按生成顺序查看不同的值,请使用
dict
(具有插入顺序)并列出:

out = list({
    reduce(lambda x, y: x.replace(y[0], y[1]), repls, text): 1
    for n in range(len(gReplMap) + 1)
    for repls in combinations(gReplMap.items(), n)
})
然后:


注意:在原始问题的预期结果中,
'test1'
的所有变体似乎都是小写的,但您的示例代码或问题文本似乎都没有指定。当然,如果需要,请在reduce之后使用
.lower()

您不应该遍历字典,而应该遍历文本的字母。这里有一个不使用itertools的解决方案

text = "Test1"
gReplMap = { 'a': '@', 'e': '3', 'i': '1', 'o': '0', 't': '+',
         'A': '@', 'E': '3', 'I': '1', 'O': '0', 'T': '+'}
lst = [text]
#Iterate through each letter in each word in lst and update the lst
for string in lst:
    for letter in string:
        if letter in gReplMap:
            new_string = string.replace(letter, gReplMap[letter])
            if new_string not in lst:
                lst.append(new_string)
print(lst)

打印循环外的列表。哦,是的,对了,忘了那个。但是我仍然得到了错误的字符串列表<代码>['test1','t3st1','t3st1','t3st1','+3s+1','+3s+1','+3s+1','+3s+1','+3s+1','+3s+1']
如何从首字母
文本='test1'
生成
(小写)呢?非常有魅力,谢谢。
text = "Test1"
gReplMap = { 'a': '@', 'e': '3', 'i': '1', 'o': '0', 't': '+',
         'A': '@', 'E': '3', 'I': '1', 'O': '0', 'T': '+'}
lst = [text]
#Iterate through each letter in each word in lst and update the lst
for string in lst:
    for letter in string:
        if letter in gReplMap:
            new_string = string.replace(letter, gReplMap[letter])
            if new_string not in lst:
                lst.append(new_string)
print(lst)