“列表索引超出范围";错误 [英] "List index out of range" error

查看:474
本文介绍了“列表索引超出范围";错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python编写一个程序,该程序将采用一小段二进制代码并根据密钥对其进行加密.如果代码段短于关键码,则必须采用关键码的最后一位,因此是两次反向.尝试将密钥的最后一部分添加到空白列表时,出现了我的问题,它给了我列表索引超出范围"的错误.代码如下:

I am writing a program in Python that will take a snippet of binary and encrypt it according to a key. If the snippet is shorter than the key, it has to take the last bit of the key, hence the double reverse. My problem comes when trying to add the last piece of the key to a blank list, where it gives me the "list index out of range" error. Code is as follows:

def OTP(msg,clave):
encList = []
encr = ''
clist = list(clave)
clist.reverse()
cutlist = []
mlist = list(msg)
mlist.reverse()
for i in range(len(msg)):
    cutlist.append(clist[i])
for i in mlist:
    for j in cutlist:
        if i == j:
            encList.append(0)
        if 1 != j:
            encList.append(1)
encList.reverse()
for i in encList:
    encr += str(encList[i])
return encr

clave = '000000010011010010001001000110110011001101010011100101010000101100111110000010100000011010010000101100000101100011010110100000100110001011001101101110110101000010000010100101000101101101010010001100001100100010111111111110010011101110010101110100111110000001101111110010000000101011000101111110100100101000110010111001100110011010100011011001101010011111100101'
msg = '01101000011010000110100001101000'

cript = OTP(msg,clave)
rev = OTP(cript,clave)
print(rev)

我给它消息的长度范围,应该在更长的密钥范围之内.一如既往,我们将不胜感激.

I am giving it the range of the length of the message, which should be within the range of the much longer key. As always, any help would be appreciated.

推荐答案

之所以出现此问题,是因为使用双for循环为我提供了一个列表,其中包含与msg平方的长度相等的项.认为mlist中的每个项目乘以cutlist中的每个项目.

The problem arose because by using a double for loop gave me a list with a number of items equal to the length of msg squared, because it considered each item in mlisttimes each item in cutlist.

这意味着当第二次调用该函数(以解密消息并确认程序正常运行)时,msg参数比clave参数长得多,从而产生错误.要解决此问题,可以使用以range(len(msg))作为参数的单个for循环,并根据cutlist[i] == mlist[i]是否将0或1添加到encr.

This meant that when the function was called a second time (to decrypt the message and confirm the program worked), the msg argument was much longer than the clave argument, cre an error. To fix this, a single for loop with range(len(msg)) as a parameter can be used, and added 0 or 1 to encr depending on whether cutlist[i] == mlist[i].

这篇关于“列表索引超出范围";错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆