Python - 嵌套循环导致索引错误

Python - Nested loops causing indexerror

我正在尝试使用二维网格密码来加密 Python 中的字符串,但我的嵌套循环导致了超出范围的错误。

这是我的代码:

def encrypt():
    before = str(input("Type a string to encrypt: "))
    columns = int(input("How many table columns would you like: "))
    split = [before[i:i+columns] for i in range(0, len(before), columns)]
    rows = len(split)
    after = []
    for i in range(0, columns):
        for j in range(0,rows):
            after.append(split[j][i])
    print(after)

这是我收到的错误:

Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    encrypt()
  File "E:/Python/cipher.py", line 12, in encrypt
    after.append(split[j][i])
IndexError: string index out of range

问题(尝试打印 split)是 split 中的所有元素不一定 rows 长:

Type a string to encrypt: hello world
How many table columns would you like: 3
['hel', 'lo ', 'wor', 'ld']

你必须决定你想做什么。如果它不够长,可以在最后一个字符串的末尾附加空格。

您可能还想看看 enumerate。快乐黑客。

更新:假设您选择使用 2 列,并且字符串长度可被二整除:

Type a string to encrypt: helo
How many table columns would you like: 2
['he', 'lo']
['h', 'l', 'e', 'o']

似乎有效。哦,我不得不稍微更改一下您的代码,因为输入不符合您的想法:

def encrypt():
    before = raw_input("Type a string to encrypt: ")
    columns = int(raw_input("How many table columns would you like: "))
    split = [before[i:i+columns] for i in range(0, len(before), columns)]
    rows = len(split)
    after = []
    for i in range(0, columns):
        for j in range(0,rows):
            after.append(split[j][i])
    print(after)

更新 2:如果要使用空格填充输入,只需添加以下行:

before += " " * (columns - len(before) % columns)

您将得到以下代码:

def encrypt():
    before = raw_input("Type a string to encrypt: ")
    columns = int(raw_input("How many table columns would you like: "))
    before += " " * (columns - len(before) % columns)
    split = [before[i:i+columns] for i in range(0, len(before), columns)]
    rows = len(split)
    after = []
    for i in range(0, columns):
        for j in range(0,rows):
            after.append(split[j][i])
    print ''.join(after)

示例输出:

Type a string to encrypt: hello world
How many table columns would you like: 4
hore llwdlo 

出现此问题是因为您输入的字符串不能保证是行的倍数。例如,使用 3 列 "Input String to Encrypt" 加密失败,因为它生成了一个拆分列表 ['Inp', 'ut ', 'Str', 'ing', 'to', 'En', 'cry', 'pt']。请注意数组中的最后一个元素只有 2 个元素。

如果您用 space 填充输入字符串,例如:"Input String to Encrypt " 加密工作作为分裂产生: ['Inp', 'ut ', 'Str', 'ing', '至', '恩', 'cry', 'pt ']

错误是由于行不能保证是规则的并且字符串长度始终不能被列数整除。

(我没有足够的声誉来 post 图片,抱歉)

http://i.stack.imgur.com/kaJJo.png

第一个网格不起作用,因为在第二个“!”之后有 4 个空格我们无法访问。第二格就可以了。