Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么索引在这个程序中会越界?_Python_List_Python 2.7_Indexoutofboundsexception - Fatal编程技术网

Python 为什么索引在这个程序中会越界?

Python 为什么索引在这个程序中会越界?,python,list,python-2.7,indexoutofboundsexception,Python,List,Python 2.7,Indexoutofboundsexception,出于某种原因,在运行此命令并输入26个字母的键时,我在Python2.7中遇到了一个错误。它说列表索引超出范围。任何帮助都将不胜感激。谢谢(我知道我可以为加密机使用一个循环) 这是我得到的完整回溯: 回溯(最近一次呼叫最后一次): 文件“translate.py”,第102行,在 userChoice() userChoice中第92行的文件“translate.py” 加密机() 文件“translate.py”,第43行,在加密机中 append(keyarray[11]) 索引器:列表索引

出于某种原因,在运行此命令并输入26个字母的键时,我在Python2.7中遇到了一个错误。它说列表索引超出范围。任何帮助都将不胜感激。谢谢(我知道我可以为
加密机使用一个循环)

这是我得到的完整回溯:

回溯(最近一次呼叫最后一次):
文件“translate.py”,第102行,在
userChoice()
userChoice中第92行的文件“translate.py”
加密机()
文件“translate.py”,第43行,在加密机中
append(keyarray[11])
索引器:列表索引超出范围
问题在于:

for char in keystring:
    keyarray.append(char)

keystring
为空,因此keyarray也将保持为空。为了不使用Indexer,您需要一个与字母表一样长的键串(因为基本上您只是在替换字符)

问题在于:

def decrypter():
    keystring = raw_input("Please paste key: ")
    message = raw_input("Message to Decrypt: ")
您正在将值分配给局部变量,因此全局变量保持为空。如果要修改全局变量,必须声明:

def decrypter():
    global keystring, message
    keystring = raw_input("Please paste key: ")
    message = raw_input("Message to Decrypt: ")
这同样适用于
加密机

此外,在接受一些输入之前,您不能创建
keyarray


代码还存在许多其他问题。您不可能认为执行所有手动索引是最好的方法。如果您想支持128个字符的字母表,该怎么办

使用循环:

for char in message:
    for i, c in enumerate(alphabet):
        if char == c:
            messagearray.append(keyarray[i])
(而不是所有那些重复的行)

此外,字符串已经提供了一种方法来精确地执行您正试图执行的操作。它叫

你可以简单地做:

import string

table = str.maketrans(string.ascii_lowercase, keystring)
然后使用:

decrypted_text = some_encrypted_text.translate(table)
运行示例:

In [1]: import string
   ...: alphabet = string.ascii_lowercase
   ...: table = str.maketrans(alphabet, alphabet[3:]+alphabet[:3])
   ...: 

In [2]: 'hello'.translate(table)
Out[2]: 'khoor'

以上内容适用于python3+。在python2.7中,必须使用而不是
str.maketrans
。所以你必须做:

In [1]: import string
   ...: alphabet = string.ascii_lowercase
   ...: table = string.maketrans(alphabet, alphabet[3:]+alphabet[:3])
   ...: 

In [2]: 'hello'.translate(table)
Out[2]: 'khoor'

什么是回溯?请:
导入字符串;alphabet=string.ascii_小写
@DanielePantaleone,刚刚发布。谢谢。@Bakuriu刚导入,下一步?非常感谢!我已经为此挣扎了一段时间。时间限制一过,我就接受答案。看起来这可能是decrypter()的一部分。事实上,您应该修改代码以始终请求密钥,然后请求解密或加密。您可能还会发现以下有趣的内容:(我想这就是您试图构建的内容)没错,但应该初始化键串的decrypter()也不能确保执行,因此在全局变量声明中键串也可能保持为空。
In [1]: import string
   ...: alphabet = string.ascii_lowercase
   ...: table = string.maketrans(alphabet, alphabet[3:]+alphabet[:3])
   ...: 

In [2]: 'hello'.translate(table)
Out[2]: 'khoor'