簡體   English   中英

如何用所有可能的組合替換字典中列表中的字符串

[英]How to replace strings in list from a dictionary with all possible combinations

我想使用名為gRep1Map的字典替換 lst 中列出的名為test1的字符串。 它需要使用gRep1Map中的字符返回所有可能的組合。 我得到了 output,但不是我想要的。 似乎無法真正找到實現這一目標的方法。

這是我的代碼。

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)

output 如下所示。

['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 的解決方案。

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)

reduce有用的罕見案例......)

from itertools import combinations
from functools import reduce

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

生產:

>>> out
{'+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)
})

然后:

>>> out
['Test1', 'T3st1', 'Tes+1', '+est1', 'T3s+1', '+3st1', '+es+1', '+3s+1']

注意:在您的原始問題的預期結果中, 'test1'所有變體似乎都是小寫的,但您的示例代碼或問題文本似乎都沒有指定這一點。 當然,如果你想要的話,在 reduce 之后使用.lower()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM