Python –字符替换组合
给定一个字符串和字典,字符映射到替换字符值列表,在用映射值替换当前字符后构造所有可能的字符串。
Input : test_str = “geeks”, test_dict = {‘s’ : [‘1’, ‘5’], ‘k’ : [‘3’]}
Output : [‘gee31’, ‘geek1’, ‘gee35’, ‘geek5’, ‘gee3s’, ‘geeks’]
Explanation : All possible replacement of strings, e.g in ‘gee35’, k is replaced by ‘3’ and s is replaced by ‘5’.
Input : test_str = “geeks”, test_dict = {‘s’ : [‘1’], ‘k’ : [‘3’]}
Output : [‘gee31’, ‘geek1’, ‘gee3s’, ‘geeks’]
Explanation : All possible replacement of strings, e.g in ‘gee31’, k is replaced by ‘3’ and s is replaced by ‘1’.
方法:使用 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']