【问题标题】:IndexError: list index out of range - looping a list [duplicate]IndexError:列表索引超出范围 - 循环列表[重复]
【发布时间】:2023-02-08 00:57:27
【问题描述】:

我创建了一个包含 26 个项目的列表。

字母表 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l' , 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', ' y', 'z']

我希望使用将字母移动到下一个选定位置:即“hello”移动位置 5 并将文本返回为“mjqqt”

为此,我使用了“for 循环”,它也能正常工作,直到我使用字母 z,因为它是列表中的最后一项。

有没有一种方法可以在到达字母表 [25] 后循环列表以重新启动到字母表 [0] 的位置,这意味着当换档字母为“z”并按位置 5 移动时,我希望它从位置 0 重新开始返回“e”

我创建了一个函数,用于循环移动单词中的每个字母并返回加密的 cipher_text。

def encrypt(plain_text, shift_amount):
    cipher_text = ""
    for letter in plain_text:
        position = alphabet.index(letter)
        new_position = position + shift_amount
        cipher_text += alphabet[new_position]
    print(f"The encoded text is {cipher_text}")
encrypt(plain_text=text, shift_amount=shift)

错误: 追溯(最近一次通话): 文件“\caesar-cipher\caesar-cipher-4 Final.py”,第 36 行,位于 加密(纯文本=文本,shift_amount=shift)

IndexError:列表索引超出范围

【问题讨论】:

  • 所以如果字母是 z (25) 并且移位是 5,那就是 IndexError
  • 正确的。这就是为什么我需要知道我们是否可以通过将 alphabet[25] + shift 移动 5(即 alphabet[30])来使其工作,就像将它移动到列表的第 4 位而不是寻找第 30 位的项目一样

标签: python-3.x list loops index-error


【解决方案1】:

很确定你可以用模来做到这一点:

def encrypt(plain_text, shift_amount):
cipher_text = ""
for letter in plain_text:
    position = alphabet.index(letter)
    new_position = (position + shift_amount) % len(alphabet)
    cipher_text += alphabet[new_position]
print(f"The encoded text is {cipher_text}")

这应该按您预期的那样工作,如果它超过了字母表的长度,您只需循环索引

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 2011-10-31
    • 2015-06-26
    相关资源
    最近更新 更多