You need to enable JavaScript to run this app. Python新手求助:append元素后的列表打印时缺失最后一项怎么解决
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:append元素后的列表打印时缺失最后一项怎么解决

问题根因

缺失最后一条答题记录是因为记录追加的逻辑位置错误,核心有两个问题:

  • 每道题答完后,代码先判断「是否答完指定题数」再执行追加操作,如果刚好答完最后一题,会直接触发break跳出循环,完全走不到追加语句,最后一条记录就丢失了
  • 答错的分支里额外写了一次game_summary.append(question_outcome),会导致非最后一题的答错记录重复存储2次

修复方案

修改主逻辑里的答题结果处理部分,按两步调整:

  1. 删掉答错分支里的多余追加代码
  2. 把追加操作移到打印答题结果之后、判断是否结束循环之前,保证每道题答完先存记录再做结束判断

调整后的对应代码片段

首先删除答错分支里的多余追加:

else:
                result = "Incorrect"
                question_outcome = "Question {} | Result: {} | Your Answer: {} | Correct Answer: {}".format(number_of_questions_answered + 1, result, response, answer)
                print()
                number_of_questions_answered += 1
                questions_answered_incorrect += 1
                # 删掉这行多余的 game_summary.append(question_outcome)

再调整追加操作的位置:

print(question_outcome)
            # 新增:每道题答完立刻追加记录,不管是不是最后一题
            game_summary.append(question_outcome)

            #End game if the number of rounds has been played
            if number_of_questions_answered == user_choice_of_questions:
                number_of_questions_answered = 0
                break


            #If the number of rounds played is more than or equal to
            #One the User will be asked if they wish to continue the game or if they wish to
            #Quit the game they should input 'xxx'
            if number_of_questions_answered >= 1:
                print()
                game_loop = continue_game("Press <Enter> if you wish to continue the game, if you wish to quit type 'xxx': ")
                print()

            #If the User inputs 'xxx' when they are asked if they want to continue the game or not
            #The Game Loop will end
            #The number of questions the User answered will be reset to 0
            if game_loop == "xxx":
                number_of_questions_answered = 0
                break

            # 删除原来放在这里的追加语句,避免重复

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 06:15:01