考虑到以下代码:
list = [1, 0 ,3]
def decrypt(text, alphabet):
decrypt_final = ""
for j in alphabet:
aindex = alphabet.index(j)
for i in list:
if aindex == i:
decrypt_final = decrypt_final + str(j)
print(decrypt_final)
decrypt("103", "abcde")当代码运行时,结果是"abd",这不是我想要的。我试图根据"abcde"的字母表范围解密数字103,如果输入是"103",正确的结果应该是"103"。
我上面的代码想要做的是查看列表(列表中的数字来自另一个函数,我并没有将其简化),如果列表号与字母表的索引相匹配,则输出字母表。不幸的是,输出顺序是错误的。
会感谢你的指导。
发布于 2020-02-08 08:24:45
我想以下几点应该能用
def decrypt(text, alphabet):
decrypt_final = ""
# convert text to list of indices
str_to_int = [int(i) for i in text]
for j in str_to_int:
decrypt_final += alphabet[j]
print(decrypt_final)
decrypt("103", "abcde")您只需将文本("103")转换为索引列表。
发布于 2020-02-08 08:29:09
你可以试试这个。
您可以通过索引来提取所需的内容。您所需要做的就是将字符串103转换为整数。可以通过执行int(str_num)将字符串数字转换为整数。一旦这些是整数,它们就是要提取的字母字符串的索引。以上所有步骤都可以浓缩成下面的代码。
'delimiter'.join(iterable)用分隔符连接可迭代元素中的所有元素。
def decrypt(txt,alphabets):
cipher_text=[alphabets[int(i)] for i in txt]
return ''.join(cipher_text)decrypt('103','abcde')
#'bad'https://stackoverflow.com/questions/60125074
复制相似问题