【问题标题】:how to fix ValueError: list index out of range如何修复 ValueError:列表索引超出范围
【发布时间】:2019-10-02 04:17:22
【问题描述】:

我不断收到此错误:

第 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

我不确定如何修复错误。有什么想法吗?

【问题讨论】:

  • 对于 message 和 int 的什么值,您会收到错误消息。能否提供一个测试用例。
  • print(encode("hello", 1)) # => 你好
  • 嘿蚂蚁。请取消删除您的代码审查请求。我写了一篇相当大的评论,希望不要浪费。

标签: python-3.x pycharm index-error


【解决方案1】:

当 key 为 1 或 key 大于字符串的长度时,返回字符串。做任何处理都没有意义。

就在该行之后

message = message.replace(" ", "_")

你可以检查条件

if key == 1 or key > len(message):
    return message

【讨论】:

  • 如何解决这个问题
猜你喜欢
  • 2019-09-15
  • 2019-10-01
  • 1970-01-01
  • 2013-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多