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

Python开发漫威问答程序:如何实现无序答案匹配?

实现漫威问答程序的无序答案匹配

你当前的漫威问答程序中,"说出银河护卫队所有成员的名字"这道题只能匹配固定顺序的答案,要实现无序匹配,推荐用集合比对的方式处理,以下是具体修改方案:

核心思路

利用集合「无序、自动去重」的特性,将正确答案和用户输入都转换为集合后直接比对,只要用户输入包含所有正确成员且无多余内容,就判定为正确。

修改后的代码

# 定义正确的银河护卫队成员集合
correct_members = {"Star Lord", "Gamora", "Rocket", "Drax", "Groot", "Mantis", "Nebula"}

answer = input("9. What are the names of all the guardians from Guardians of the Galaxy? ")

# 处理用户输入:分割成单个成员,去除前后空格,转成集合
user_members = {member.strip() for member in answer.split(",")}

# 比对两个集合是否完全一致
if user_members == correct_members:
    print("Correct!")
else:
    print("Incorrect!")

优化补充(可选)

如果想支持不区分大小写的匹配(比如用户输入"star lord"也能识别),可以将集合和输入都统一转为小写:

correct_members = {"star lord", "gamora", "rocket", "drax", "groot", "mantis", "nebula"}

answer = input("9. What are the names of all the guardians from Guardians of the Galaxy? ")
user_members = {member.strip().lower() for member in answer.split(",")}

if user_members == correct_members:
    print("Correct!")
else:
    print("Incorrect!")

替代方案:排序后比对

若不想使用集合,也可以将正确列表和用户输入处理后都排序,再比对排序后的结果:

correct_members = ["Star Lord", "Gamora", "Rocket", "Drax", "Groot", "Mantis", "Nebula"]
correct_sorted = sorted(correct_members)

answer = input("9. What are the names of all the guardians from Guardians of the Galaxy? ")
user_members = [member.strip() for member in answer.split(",")]
user_sorted = sorted(user_members)

if user_sorted == correct_sorted:
    print("Correct!")
else:
    print("Incorrect!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 21:47:00