这里有两个字符串:
d = '123'
list1 = '12345'
显然,d中包含三个元素,分别是'1'、'2'、'3'。 现在,尝试使用 list1 中的元素替换这三个元素。并打印出所有可能的组合。
因此,我们可以将“1”替换为“1”、“2”、“3”、“4”、“5”,但不要忘记我们需要对“2”做同样的事情和 d 中的“3”。
那么结果会是这样的:
'111', '112', '113', '114', '115'
'121', '122', '123', '124', '125'
...
...
...
'541', '542', '543', '544', '545'
'551', '552', '553', '554', '555'
非常感谢@tobais_k 的提醒,这个问题可以描述为“输入中的相等字符映射到输出中的相等字符”。
因此,如果我们有 d1 = '111222333'
,输出将是
'111111111', '111111222', '111111333', '111111444', '111111555',
'111222111', '111222222', ...,
'555555111', '555555222', '555555333', '555555444', '555555555'
如果d2 = '123123123'
,d1的情况会很不一样,因为我们无法从d2得到'111111222'。结果将是:
'111111111', '112112112', '113113113', '114114114', '115115115',
'121121121', '122122122', '123123123', '124124124', '125125125',
...
'551551551', '552552552', '553553553', '554554554', '555555555'
这是我给出上述结果的代码:
d = '123'
list1 = '12345'
list2 = sorted(set(d))
# make a dict to recognize the position of each element
position = {}
for i in list2:
position[i] = []
for (x,y) in enumerate(d):
if y==i:
position[i].append(x)
print(position)
# in this case,it should return{'1': [0], '2': [1], '3': [2]}
for i1 in list1:
for i2 in list1:
for i3 in list1:
c = list(d)
# because we know the exact position for each element
# then we make a new list every time
# just replace the right element at the right place
f = [i1, i2, i3]
j = 0
for (k,v) in position.items():
for x in v:
c[x]=f[j]
j += 1
print(''.join(y for y in c))
您可能希望尝试 d = '123123123'
或 d = '111222333'
来检查结果,但请注意它们是几个嵌入的“for”在代码中并使这段代码不那么 Pythonic。
是否有更优雅的方式来给出相同的结果?
我的代码看起来有点笨拙,毫无疑问我可以从你那里学到更多;那么,这项技能在其他情况下会有所帮助,例如我们有一个复杂的 encryptedD ='bccle', key = 'ap';通过这个简单的程序,我们可能会发现 D 实际上是“苹果”的意思。
最佳答案
试用产品:
import itertools
s = '12345'
["".join(p) for p in itertools.product(s, repeat=3)]
如果您想使用 d = '123'
,您可以将 repeat 参数更改为 len(d)
。
问题已更新,替代解决方案是:
import itertools
s = '12345'
d = '111222333'
[''.join(dict(zip(set(d),p))[k] for k in d) for
p in itertools.product(s, repeat=len(set(d)))]
但是..我跑了一些小时间,接受的答案更快。所以我会坚持这一点。
关于python - 如何优雅地替换字符串中的每个元素(字符)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47837745/