我正在尝试构建基本的编码器和解码器以学习一些Python。那是我目前的代码:

import time

def mainSub():
    sString = input('Please enter a string:')
    sChoose = input('Would you like to [e]ncrypt or [d]ecrypt?:')
    encrypts = ["a","362","b","637","c","391","d","678","e","912","f","718","g","461","h","888","i","123","j","817","k","571","l","111","m","036","n","182","o","951","p","711","q","500","r","125","s","816","t","183","u","619","v","678","w","911","x","719","y","567","z","678"," ","-"]
    if sChoose == "e":
        for x in range(0, len(encrypts)):
            sOutput = sString
            sOutput = sOutput.replace(encrypts[x], encrypts[x+1])
    elif sChoose == "d":
        for x in range(0, len(encrypts)):
            sOutput = sString
            sOutput = sOutput.replace(encrypts[x+1], encrypts[x])
    else:
        print("You did not choose for encrypt or decrypt. Please only enter e or d.")
        print(sOutput)

while True:
    mainSub()


但是,控制台在应替换为以下错误时中止运行:

Traceback (most recent call last):
  File "C:/Users/Max/Desktop/test.py", line 20, in <module>
  mainSub()   File "C:/Users/Max/Desktop/test.py", line 10, in mainSub
  sOutput = sOutput.replace(encrypts[x], encrypts[x+1])
IndexError: list index out of range


我找不到错误。有人能帮我吗?

最佳答案

根据其他答复,您得到了很好的旧的按索引编制的东西。一种潜在的解决方案是根本不摆弄任何索引:

# Let's put this line out of the for loop to prevent clearing changes every iteration
sOutput = sString
for current_item, next_item in zip(encrypts, encrypts[1:]):
    sOutput = sOutput.replace(current_item, next_item)


zip接受两个Iterable,并返回包含每个Iterable一项的元组,并在用尽最短的Iterable时结束。通过用encrypts压缩encrypts[1:],可以得到一系列包含encrypts中相邻元素的元组。

如果encrypts很大,则使用izip模块中的itertools会提高内存效率。完全像使用izip一样使用zip,它将返回一个延迟评估的生成器对象,而不是首先创建整个元组列表。

编辑:再次检查您的代码后,有几件事从根本上来说是错误的。我上面的内容可复制您的代码执行的操作而不会产生索引错误,但是您的代码执行的操作实际上是不正确的。实际上,您实际上需要将第一项与第二项,第三项与第四项等配对,而当前正在将第一项与第二项,第二项与第三项,第三项与第四项等配对。

这是进行加密的方法:

for odd_elem, even_elem in zip(encrypts[::2], encrypts[1::2]):
    sOutput = sOutput.replace(odd_elem, even_elem)


或就像@ padraic-cunningham所说,请使用dict,因为您一次要加密一个字符。您可以按照以下方式进行加密:

encrypt_dict = dict(zip(encrypts[0::2], encrypts[1::2]))
sOutput = ''.join(encrypt_dict[char] for char in sString)


使用字典很难解密,因为您没有将所有内容加密为3个数字(空格会转换为“-”)。它仍然是可行的,方法是先将'-'分割成小块,然后再进一步将其分别分成3个数字,然后再通过解密指令对其进行处理。或者,您可以按照@ padraic-cunningham将空格转换为“ ---”。

10-08 09:08