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

如何实现输入单词匹配指定字母输出对应形状、无匹配则重输入的功能

实现方案

核心修改思路

  • 用Python字典存储字母和对应标识的映射关系,替代零散的变量定义,查找效率更高
  • 增加无限循环逻辑,只有当输入包含有效字符并输出结果后才退出循环,否则持续提示用户重新输入
  • 遍历输入单词的每一个字符,按映射规则替换后拼接结果字符串

可直接运行的完整代码

# 定义字母到对应标识的映射字典
char_map = {
    'a': 'x',  # 对应shape1
    'b': 'y',  # 对应shape2
    'c': 'z'   # 对应shape3
}

while True:
    # 获取用户输入,去除首尾空白字符
    input_word = input("enter any single word: ").strip()
    result = []
    # 遍历每个字符做匹配替换
    for char in input_word:
        if char in char_map:
            result.append(char_map[char])
    # 拼接结果字符串
    output = ''.join(result)
    if output:
        print(output)
        break
    else:
        print("invalid please try again")

功能验证测试样例

  • 输入apple → 输出 x
  • 输入banana → 输出 yxxx
  • 输入kiwi → 提示 invalid please try again 并重新弹出输入框
  • 输入cab → 输出 zxy

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:18:01