📜  Python –字符替换组合

📅  最后修改于: 2022-05-13 01:55:47.386000             🧑  作者: Mango

Python –字符替换组合

给定一个字符串和字典,字符映射到替换字符值列表,在用映射值替换当前字符后构造所有可能的字符串。

方法:使用 zip() + 列表理解 + replace() + product()

上述功能的组合可以用来解决这个问题。在此,我们使用 product 提取所有组合字符,并使用 zip() 一次配对一个,使用 replace() 替换。

Python3
# Python3 code to demonstrate working of 
# Character Replacement Combination
# Using zip() + list comprehension + replace() + product()
from itertools import product
  
# initializing string
test_str = "geeks"
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing dictionary
test_dict = {'s' : ['1', '2'], 'k' : ['3']}
  
# adding original character to possible characters 
for key in test_dict.keys():
    if key not in test_dict[key]:
        test_dict[key].append(key)
  
res = []
  
# constructing all possible combination of values using product
# mapping using zip()
for sub in [zip(test_dict.keys(), chr) for chr in product(*test_dict.values())]:
    temp = test_str
    for repls in sub:
          
        # replacing all elements at once using * operator
        temp = temp.replace(*repls)
    res.append(temp)
  
# printing result 
print("All combinations : " + str(res))


输出
The original string is : geeks
All combinations : ['gee31', 'geek1', 'gee32', 'geek2', 'gee3s', 'geeks']