gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:59:59 27 4
gpt4 key购买 nike

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

每行的长度由用户输入的按键决定,行数由用户输入的消息长度决定(+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。任何帮助将不胜感激。谢谢。

最佳答案

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

关于python - 二维列表行中的最后一个元素没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35075416/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com