簡體   English   中英

python 3.x上的列表索引超出范圍錯誤

[英]List Index Out Of Range Error on python 3.x

錯誤信息:

追溯(最近一次通話最近):文件“ C:\\ Users \\ Name \\ Desktop \\ transpositioncipher.py”,位於cipher.append(stringList [(x * result)+ i])中的第17行

IndexError:列表索引超出范圍

我正在制作轉置密碼來加密字符串。 稍后我將進行解密。

我一直遇到這個錯誤,沒有運氣修復它。 如果輸入文本為“四個”,則輸出應為[f,u,o,r]。

import math

stringToEnc = input("String to encrypt: ")
stringList = list(stringToEnc.replace(" ", ""))
letterCount = len(stringList)

encrypted = []
result = letterCount

for i in range(2, int(math.sqrt(letterCount))+1):
        if letterCount % i == 0:
            result = i
            break
i = 0
while i != letterCount:
        for x in range(result):
                encrypted.append(stringList[(x*result)+i])
        i+=1

print(encrypted)

如果您在調試器中查找,或者將print ((x*result) + i)到while循環中,您將看到print ((x*result) + i)在for循環的第3次迭代中返回4。 長度為4的stringList超出限制4,但只有索引0、1、2、3。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM