![](/img/trans.png)
[英]Replacing two characters in a string with a specified set of characters to create all possible combinations
[英]Replacing a character in a string with a set of two possible characters
a = ["0$%","0%%%","0$%$%","0$$"]
上面是一个损坏的通信代码,其中每个序列的第一个元素被伪装为 0。我想通过计算所有可能序列的列表来恢复原始和正确的代码,方法是用 $ 或 % 替换 0,然后检查哪个序列有效。 如果正确,可以将每个序列视为对应于一个字母表。 例如,“$$$”可以对应字母“B”。
这是我到目前为止所做的
raw_decoded = []
word = []
for i in a:
for j in i:
if j == "0":
x = list(itertools.product(["$", "%"], *i[1:]))
y = ("".join(i) for i in x)
for i in y:
raw_decoded.append(i)
for i in raw_decoded:
letter = code_dict[i] #access dictionary for converting to alphabet
word.append(letter)
return word
不确定您的意思,也许您可以添加所需的输出。 我从你的问题中得到的可以通过以下方式解决:
b = []
for el in a:
if el[0] == '0':
b.append(el.replace('0', '%', 1))
b.append(el.replace('0', '$', 1))
else:
b.append(el)
试试看:
output = []
for elem in a:
replaced_dollar = elem.replace('0', '$', 1)
replaced_percent = elem.replace('0', '%', 1)
# check replaced_dollar and replaced_percent
# and then write to output
output.append(replaced_...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.