二维列表行中的最后一个元素没有更改

2024-04-26 18:00:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维的列表,我在上面迭代,以改变用户输入的元素。你知道吗

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

例如,如果我输入“frank”作为键,输入“how are you”作为消息,我希望得到以下输出:

[[(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。任何帮助都将不胜感激。非常感谢。你知道吗


Tags: thekeyinboxmessageforgetindex
1条回答
网友
1楼 · 发布于 2024-04-26 18:00:07

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

相关问题 更多 >