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

Python for循环中如何避免随机生成的唯一题目重复及答案泄露

问题修复方案

核心修改点

  • 预生成所有词对的索引列表打乱后取用,每次出题消耗2个未使用的索引,从根源避免重复选取同一个词对,自然规避过往题目泄露答案的问题
  • 修正原代码中indexes = range(len(wordlist1 and wordlist2))的错误写法,该写法实际只会取wordlist2的长度,改为直接取两个列表的等长索引范围
  • 新增得分统计变量和错题存储列表,10道题答完后统一输出得分和所有答错题目对应的正确答案
  • 增加题目标号显示,符合需求要求的Q1、Q2格式

注:当前词对总数为17组,每道题消耗2组不同词对,最多可出8道不重复且无答案泄露的题。如果需要稳定出10道题,可以将两个词表扩充到20组以上的反义词对即可。

修复后完整代码

import random

wordlist1 = ["hot", "summer", "hard", "dry", "simple", "light", "weak", "male", "sad", "win", "small", "ignore", "buy", "succeed", "reject", "prevent", "exclude"]
wordlist2 = ["cold", "winter", "soft", "wet", "complex", "darkness", "strong", "female", "happy", "lose", "big", "pay attention", "sell", "fail", "accept", "allow", "include"]

# 预生成所有索引并打乱
available_indexes = list(range(len(wordlist1)))
random.shuffle(available_indexes)

score = 0
wrong_questions = []
# 可出的最大题数为词对总数//2,这里取需求的10和最大题数的较小值,避免报错
total_question = min(10, len(available_indexes)//2)

for q_num in range(1, total_question + 1):
    # 每次取两个不同的未使用索引
    idx1 = available_indexes.pop()
    idx2 = available_indexes.pop()
    # 生成题目
    question = f"Q{q_num}: {wordlist1[idx1]} is to {wordlist2[idx1]}, as {wordlist1[idx2]} is to .... ?"
    user_ans = input(question).strip().lower()
    correct_ans = wordlist2[idx2]
    if user_ans == correct_ans:
        score += 1
        print("回答正确")
    else:
        print("回答错误")
        # 存储错题信息
        wrong_questions.append({
            "question": question,
            "your_ans": user_ans,
            "correct_ans": correct_ans
        })

# 输出最终结果
print(f"\n最终得分:{score}/{total_question}")
if wrong_questions:
    print("\n答错的题目:")
    for idx, wrong in enumerate(wrong_questions, 1):
        print(f"{idx}. 题目:{wrong['question']}")
        print(f"   你的答案:{wrong['your_ans']},正确答案:{wrong['correct_ans']}\n")

逻辑说明

因为每次出题都会把用到的两个索引从可用列表里永久移除,所有词对只会被使用一次,既不会出现重复题目,也不会出现某道题的答案在之前的题目里已经出现过的情况,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:15:01