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

Python凯撒密码开发:如何将字符映射到字母列表索引?

解决方案

假设你已经定义了包含A-Z的cache列表(比如cache = [chr(ord('A') + i) for i in range(26)]),可以用列表推导式快速实现需求:

# 先定义你的cache列表(如果还没定义的话)
cache = [chr(ord('A') + i) for i in range(26)]

def get_char_indices(rawmessage):
    # 遍历输入字符串的每个字符,取其在cache中的索引
    return [cache.index(char) for char in rawmessage]

测试示例

  • 输入'AAA',调用get_char_indices('AAA')会返回[0, 0, 0]
  • 输入'ABC',调用get_char_indices('ABC')会返回[0, 1, 2]

额外优化(可选)

如果你的输入可能包含小写字母或者非字母字符,可以调整函数来兼容:

def get_char_indices(rawmessage):
    result = []
    for char in rawmessage:
        upper_char = char.upper()
        if upper_char in cache:
            result.append(cache.index(upper_char))
    return result

这个版本会自动把小写转成大写,同时忽略非A-Z的字符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:24:19