列表索引超出范围时如何循环遍历列表?以凯撒密码实现为例
移位密码环形索引实现方案
核心实现逻辑
无需通过复制字母表扩容的方式解决索引越界,直接利用Python的取模运算即可实现循环移位效果,这是处理环形列表索引最高效的方案:
- 无论计算得到的索引多大,经过
% 列表总长度的运算后,结果都会自动映射到列表的有效索引范围内,实现超出尾部就回到开头循环的效果。 - 核心计算公式:
有效新索引 = (原字母位置 + 移位值) % 字母表长度
原代码存在的问题
- 越界判断阈值错误:26个字母的有效索引范围是0-25,当新索引等于26时就已经触发越界,原代码中
if new_position > len(alphabet)的判断漏掉了边界值场景。 - 条件块内的循环代码存在语法错误,完全没有实现索引绕回的计算逻辑。
优化后可直接运行的完整代码
alphabet = ['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'] direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n") text = input("Type your message:\n").lower() shift = int(input("Type the shift number:\n")) # 提前对移位值做取模校准,避免移位值远大于26时的冗余计算 shift = shift % len(alphabet) def caesar(start_text, shift_amount, cipher_direction): end_text = "" for letter in start_text: # 直接保留文本中的非字母字符,避免触发查找索引的报错 if letter not in alphabet: end_text += letter continue position = alphabet.index(letter) if cipher_direction == "decode": # 解密反向移位同样适配取模规则,负数偏移不会触发越界 new_position = (position - shift_amount) % len(alphabet) else: new_position = (position + shift_amount) % len(alphabet) end_text += alphabet[new_position] print(f"Your {cipher_direction}d result: {end_text}") caesar(start_text=text, shift_amount=shift, cipher_direction=direction)
常见场景验证
- 输入字母
z、移位值1:新位置计算为(25 + 1) % 26 = 0,对应字母a,无越界报错。 - 输入字母
a、移位值30:新位置计算为(0 + 30) % 26 = 4,对应字母e,自动完成4次循环偏移的计算。
内容的提问来源于stack exchange,提问作者timmyx
相关产品推荐
相关产品推荐

