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

Python trivia问答游戏随机出题去重时列表追加失效问题求解

问题解决方法

核心问题原因

  • 你定义的三个问题函数没有显式返回值,执行random.choice(my_list)()时会先调用函数,得到的返回值固定为None,存到appendedList里的都是相同的None,自然无法实现去重
  • 逻辑顺序错误:你是先调用问题函数出题,再做去重校验,就算校验到重复也已经出过题了,不符合需求

解决方案(无需整数ID)

Python中函数本身是一等对象,可以直接作为元素存入列表,也可以直接用in判断是否存在,不需要额外分配ID。调整逻辑为:先选未使用过的问题函数,再调用执行即可。

修正后代码

import random

def question1():
    answerOne = str(input("What is the 2nd planet from the sun? "))
    if answerOne == "Venus":
        print("Correct!")
    else:
        print("Incorrect")
        print("The correct answer is Venus")

def question2():
    answerTwo = int(input("How many planets are there? "))
    if answerTwo == 8:
        print("Correct!")
    else:
        print("Incorrect")
        print("The correct answer is 8")

def question3():
    answerThree = int(input("How many miles per sec does light travel? "))
    if answerThree == 186000:
        print("Correct!")
    else:
        print("Incorrect")
        print("The correct answer is 186000")

# 所有待选问题函数列表
question_pool = [question1, question2, question3]
# 已使用的问题函数记录
used_questions = []

while True:
    # 先判断是否还有可用题目
    if len(used_questions) == len(question_pool):
        print("所有题目已出完!")
        break
    begin = int(input("Next question? 1 = Yes, 2 = No "))
    if begin == 2:
        break
    if begin == 1:
        # 过滤得到未使用的问题列表
        available_questions = [q for q in question_pool if q not in used_questions]
        # 随机选一个未使用的问题
        selected_q = random.choice(available_questions)
        # 先标记为已使用
        used_questions.append(selected_q)
        # 再调用出题
        selected_q()

改动说明

  • 移除了无用的变量a,改为通过判断已用列表长度和题目池长度是否相等,自动结束循环
  • 调整执行顺序:先筛选未使用的问题、选中后先加入已用列表,再调用函数出题
  • 直接使用函数本身作为去重判断的依据,不需要额外ID
  • 优化了多余的elif判断,直接用else简化代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:18:03