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

Python如何将元音a、e后紧跟的字母追加到去重列表并存储为字典

代码修正方案

原代码存在的问题

  • 未初始化目标字典vowel_dict,定义了冗余的空列表a、e
  • 循环中误把索引i当成字符判断,且没有做边界校验,i+1会超出字符串下标范围引发报错
  • 每次匹配到字符就重新给对应键赋值为空列表,会覆盖之前存储的内容
  • 追加的是当前的a/e字符本身,不符合取后续字符的需求
  • 没有去重逻辑,同时存在print语法错误

修正后可运行代码

text = 'there is a sea apple'
# 初始化目标字典,两个键对应空列表
vowel_dict = {'a': [], 'e': []}

# 遍历范围减1,避免i+1越界
for i in range(len(text) - 1):
    current_char = text[i]
    next_char = text[i+1]
    # 只处理a/e的情况,且后续字符是字母
    if current_char in ('a', 'e') and next_char.isalpha():
        # 去重:只有当前字符不在列表里才追加
        if next_char not in vowel_dict[current_char]:
            vowel_dict[current_char].append(next_char)

print(vowel_dict)

输出结果

{'a': ['p'], 'e': ['r', 'a']}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:54:03