You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现凯撒密码时列表.append()仅替换元素不新增如何解决

凯撒密码加密代码问题修复

问题根因

你代码里的encrypted空列表被定义在了for循环内部,每遍历一个字符就会重新初始化一个空列表覆盖之前的列表对象,因此.append()每次都是向新的空列表添加元素,循环结束后仅保留最后一次遍历生成的列表,自然只能得到最后一位的加密结果。

修复方案

将encrypted = []移动到for循环外部即可,修复后的完整代码如下:

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']

text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))

def encrypt(text,shift):
    # 空列表移到循环外,仅初始化一次
    encrypted = []
    for letter in text:
        # 增加模26处理,避免偏移量超过26时索引越界报错
        position = (alphabet.index(letter) + shift) % 26
        encrypted.append(alphabet[position])
    print(''.join(encrypted))
    
encrypt(text,shift)

补充说明

新增的%26取模操作是为了兼容偏移量大于26的场景,比如输入shift为30时,等价于偏移4位,不会出现列表索引越界的报错。

内容的提问来源于stack exchange,提问作者razu380

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 17:36:01