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
相关产品推荐
相关产品推荐

