如何不从外部文本文件中打印重复的行?

时间:2019-04-08 20:42:04

标签: python python-3.x

我正在尝试使用python创建多项选择测验。我有一个外部.txt文件,其中包含20个问题,并且我希望它从该文件中选择10个随机问题,目前它正在这样做。该文件具有以下布局:

1,谁是第一个在月球上行走的人?,迈克尔·杰克逊(A.Michael Jackson),巴斯·布赖特(Buzz Lightyear),尼尔·阿姆斯特朗(Neil Armstrong),没人(D.Nobody)和

我遇到的问题是我不希望它两次打印相同的问题。

我认为解决此问题的唯一方法是在Python定义的列表中添加作为问题编号的detail [0],然后在该列表中进行检查以确保问题编号不重复。

import random
qno = []
def quiz():
    i = 0
    global score #makes the score variable global so it can be used outside of the function
    score=0 #defines the score variable as '0'
    for i in range (1,11): #creates a loop that makes the program print 10 questions
        quiz=open('space_quiz_test.txt').read().splitlines() #opens the file containing the questions, reads it and then splits the lines to make them seperate entities
        question=random.choice(quiz)
        detail = question.split(",")
        print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
        print(" ")
        qno.append(detail[0])
        print(qno)
        if detail[0] in qno is False:
            continue
            qno.append(detail[0])
            print(qno)
        elif detail[0] in qno is True:
            if detail[0] not in qno == True:
                print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5]) 
                print(" ")
                qno.append(detail[0])
                print(qno)
        while True:
            answer=input("Answer: ")
            if answer.upper() not in ('A','B','C','D'):
                print("Answer not valid, try again")
            else:
                break
        if answer.upper() == detail[6]:
            print("Well done, that's correct!")
            score=score + 1
            print(score)
            continue
        elif answer.upper() != detail[6]:
            print("Incorrect, the correct answer is ",detail[6])
            print(score)
            continue

quiz()

当我运行这段代码时,我希望没有重复两次的问题,但是它似乎总是可以做到的,我正在努力想办法。任何帮助将不胜感激,谢谢!

5 个答案:

答案 0 :(得分:1)

使用此:

questions = random.sample(quiz, 10)

它将从测验列表中选择一个长度为10的随机子列表。

也:

您应该阅读文件,并在循环之外添加问题列表,然后循环浏览问题:

with open('space_quiz_test.txt') as f:
    quiz = f.readlines()

questions = random.sample(quiz, 10)
for question in questions:
    ...

答案 1 :(得分:1)

与其打开文件10次,不如从文件中获取10个问题并循环询问:

def get_questions(fn, number):
    with open(fn) as f:

        # remove empty lines and string the \n from it - else you get 
        # A\n as last split-value - and your comparisons wont work
        # because A\n != A
        q = [x.strip() for x in f.readlines() if x.strip()]
    random.shuffle(q)
    return q[:number]


def quiz():
    i = 0 
    global score # makes the score variable global so it can be used outside of the function
    score=0 # defines the score variable as '0'

    q = get_questions('space_quiz_test.txt', 10) # gets 10 random questions
    for question in q:
        detail = question.split(",")
        print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
        print(" ")
        # etc ....

Doku:


还有其他几项要修复:

# global score  # not needed, simply return the score from quiz():
my_score = quiz() # now my_score holds the score that you returned in quiz()
...

# logic errors - but that part can be deleted anyway:
elif detail[0] in qno is True:       # why `is True`? `elif detail[0] in qno:` is enough
    if detail[0] not in qno == True:    # you just made sure that `detail[0]` is in it

... 


 while True:
        answer=input("Answer: ").upper()           # make it upper once here
        if answer not in ('A','B','C','D'):        # and remove the .upper() downstream
            print("Answer not valid, try again")
        else:
            break

答案 2 :(得分:1)

您可以一次选择绘制所有问题而无需替换,然后反复遍历这些问题。

import numpy as np
quiz=open('space_quiz_test.txt').read().splitlines() #opens the file containing the questions, reads it and then splits the lines to make them seperate entities
questions=np.random.choice(quiz, size=10, replace=False)
    for question in quesions: #creates a loop that makes the program print 10 questions
         #rest of your code

答案 3 :(得分:1)

阅读所有问题:

with open('space_quiz_test.txt') as f:
    quiz = f.readlines() 

随机播放问题列表:

random.shuffle(quiz)

在随机列表上循环:

for question in quiz:
    print(question)

答案 4 :(得分:1)

这是因为random.choice可以多次提供相同的输出。而不是使用random.choice试试 random.shuffle(list),然后从随机列表中选择前10条记录。

quiz=open('space_quiz_test.txt').read().splitlines()
random.shuffle(quiz)
for question in quiz[1:11]:
        detail = question.split(",")
        print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])