how to fix ValueError: list index out of range
how to fix ValueError: list index out of range
我不断收到此错误:
第 23 行,在编码中
raw_out[i][pos] = 消息[pos]
IndexError: 列表索引超出范围
这部分节目:
def encode(message: str, key: int) -> str:
"""
Encode text using Rail-fence Cipher.
Replace all spaces with '_'.
:param message: Text to be encoded.
:param key: Encryption key.
:return: Decoded string.
"""
message = message.replace(" ", "_")
down = True
raw_out = []
out = ''
i = 0
for x in range(key):
raw_out.append({})
for pos in range(len(message)):
raw_out[i][pos] = message[pos]
if i == key - 1:
down = False
if i == 0:
down = True
if down:
i = i + 1
else:
i = i - 1
for p in raw_out:
for q in p:
out += p[q]
return out
我不确定如何修复错误。有什么想法吗?
当键为一或当键大于字符串的长度时 return 字符串原样。做任何处理都没有意义。
在行
之后
message = message.replace(" ", "_")
你可以检查条件
if key == 1 or key > len(message):
return message
我不断收到此错误:
第 23 行,在编码中 raw_out[i][pos] = 消息[pos] IndexError: 列表索引超出范围
这部分节目:
def encode(message: str, key: int) -> str:
"""
Encode text using Rail-fence Cipher.
Replace all spaces with '_'.
:param message: Text to be encoded.
:param key: Encryption key.
:return: Decoded string.
"""
message = message.replace(" ", "_")
down = True
raw_out = []
out = ''
i = 0
for x in range(key):
raw_out.append({})
for pos in range(len(message)):
raw_out[i][pos] = message[pos]
if i == key - 1:
down = False
if i == 0:
down = True
if down:
i = i + 1
else:
i = i - 1
for p in raw_out:
for q in p:
out += p[q]
return out
我不确定如何修复错误。有什么想法吗?
当键为一或当键大于字符串的长度时 return 字符串原样。做任何处理都没有意义。
在行
之后message = message.replace(" ", "_")
你可以检查条件
if key == 1 or key > len(message):
return message