Python 二维列表行中的最后一个元素未更改
我有一个二维列表,我在它上面迭代,以改变用户输入的元素 每行的长度由用户输入的键决定,行的数量由用户输入的消息的长度决定(+1,因为第一行填充了ASCII值,出于其他原因需要在那里) 例如,如果我输入“frank”作为键,输入“how are you”作为消息,我希望得到以下输出:Python 二维列表行中的最后一个元素未更改,python,python-3.x,multidimensional-array,Python,Python 3.x,Multidimensional Array,我有一个二维列表,我在它上面迭代,以改变用户输入的元素 每行的长度由用户输入的键决定,行的数量由用户输入的消息的长度决定(+1,因为第一行填充了ASCII值,出于其他原因需要在那里) 例如,如果我输入“frank”作为键,输入“how are you”作为消息,我希望得到以下输出: [[(ASCII values], ['h', 'o', 'w', 'a', 'r'], ['e', 'y', 'o', 'u', 0] 但我得到的却是: [[(ASCII values], ['h', 'o',
[[(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不能存在。
之后,您将获得一个超出范围的索引,用于尝试访问不存在的消息位置。到达消息末尾时,必须提前停止循环
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
您可以使用list.append(element)
,这样您就不需要像[0]*key\u length这样的东西了。使用理解列表,您可以在一行中创建ascii\u列表ascii\u列表=[ord(char)for char in keyword]
谢谢furas。我总是忽略列表的理解,因为我不经常使用它们。