2D列表行中的最后元素不会更改

时间:2016-01-29 01:34:15

标签: python python-3.x multidimensional-array

我有一个二维列表,我正在迭代它以改变用户输入的元素。

每行的长度由用户输入的密钥确定,行数由用户输入的消息长度决定(+ 1,因为第一行填充了需要的ASCII值那里有其他原因)

例如,如果我输入“frank”作为键,并且“你好吗”作为消息,我想得到输出:

[[(ASCII values], ['h', 'o', 'w', 'a', 'r'], ['e', 'y', 'o', 'u', 0]

但我得到了:

[[(ASCII values], ['h', 'o', 'w', 'a', '0'], ['r', 'e', 'y', 'o', 0]

以下是代码:

def main():
    keyword = get_keyword()
    key_length = get_keyword_length(keyword)
    message = get_message()
    ascii_list = ascii_conversion(keyword, key_length)
    box = encryption_box(ascii_list, message, key_length)
    print(box)
    fill_letters(box, message, key_length)
    print(box)

# Gets the keyword to encrypt with.
def get_keyword():
    keyword = input("Enter the word you'd like to use for encryption (no duplicate letters): ").lower()
    return keyword

# Gets length of keyword
def get_keyword_length(keyword):
    key_length = len(keyword)
    return key_length

# Gets the message to encrypt and removes punctuation and spaces.
def get_message():
    message = input('Enter the message you want to encrypt: ').lower()
    message = message.replace("'", "").replace(",", "").replace(".", "").replace("!", "").replace("?", "")\
    .replace(" ", "")
    return message

# Converts keyword to ASCII
def ascii_conversion(keyword, key_length):
    ascii_list = [0] * key_length
    index = 0
    for character in keyword:
        ascii_list[index] = ord(character)
        index += 1
    return ascii_list

# Creates 2D list with correct dimensions and fills first row with the ascii numbers.
def encryption_box(ascii_list, message, key_length):
    if len(message) % len(ascii_list) != 0:
        box = [[0] * len(ascii_list) for x in range(len(message)//(len(ascii_list))+2)]
    else:
        box = [[0] * len(ascii_list) for x in range(len(message)//(len(ascii_list))+1)]
    index = 0
    for number in ascii_list:
        box[0][index] = number
        index += 1
    return box

# Fill in the message in the remaining encryption box spaces.
def fill_letters(box, message, key_length):
    len_box = len(box)
    message = list(message)
    index = 0

    for r in range(1, len_box):
        for c in range(key_length - 1):
            box[r][c] = message[index]
            index += 1

main()

看着这个:

for r in range(1, len_box):
    for c in range(key_length - 1):
        box[r][c] = message[index]
        index += 1

我觉得最终box [r] [c]将是box [1] [4]并且对应于最后一个元素,但它仍为0.任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

range有一个独占上限,所以-1不能存在。 之后,您将获得一个索引超出范围,以尝试访问不存在的消息位置。必须在到达消息结束时提前停止循环。

for r in range(1, len_box):
    for c in range(key_length):
        if index == len(message): break
        box[r][c] = message[index]
        index += 1