Python 如何从代码中随机选择一行而不重复

Python 如何从代码中随机选择一行而不重复,python,python-2.6,Python,Python 2.6,我对python非常陌生,我需要让我的程序从琐事游戏中随机选择一个问题,但之后不会重复。 这个游戏基于我收到的一本关于python的书中的问题 print "trivia game" begin = raw_input("Would you like to begin?: ") if begin == "Yes": print "A) Getting your computer to do stuff" print "B) A form of watching televisio

我对python非常陌生,我需要让我的程序从琐事游戏中随机选择一个问题,但之后不会重复。 这个游戏基于我收到的一本关于python的书中的问题

print "trivia game"
begin = raw_input("Would you like to begin?: ")
if begin == "Yes":
    print "A) Getting your computer to do stuff"
    print "B) A form of watching television"
    print "C) Building a computer"
    print "D) Assembling a computer with your bare hands"
    q1 = raw_input("What is programming?: ")
    if q1 == "A" or q1 == "a":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) African Standard Code For Information Interchange"
    print "B) American Standard Code For Information Interchange"
    print "C) American Subtle Codes For Information Interchange"
    print "D) African Subtle Codes For Inside Interchange"
    print " "
    q2 = raw_input("What does ASCII stand for?: ")
    if q2 == "b" or q2 == "B":
        print "Well done! You got it right! "
        print " "
    else:
        print "no, you're wrong! +0"
    print "A) A hidden group of words"
    print "B) A group of random letters"
    print "C) The generation of random numbers by a definite computational process. "
    print "D) The way to write code"
    q3 = raw_input("What is pseudorandom?: ")
    if q3 == "C" or q3 == "c":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) Only strings and loops"
    print "B) Only loops"
    print "C) Only strings"
    print "D) Any type"
    q4 = raw_input("What kinds of elements can you store with a tuple?: ")
    if q4 == "D" or q4 == "d":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) Yes"
    print "B) No"
    print "C) Only if they are loops"
    print "D) Only if they are strings"
    q5 = raw_input("Do variables store the values you assign to them?: ")
    if q5 == "A" or q5 == "a":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) One"
    print "B) There is no limit"
    print "C) 158,240"
    print "D) 1000"
    q6 = raw_input("How many paramters can a function have?: ")
    if q6 == "B" or q6 == "b":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) Lists of numbers"
    print "B) Complex information"
    print "C) Simple information"
    print "D) Loops"
    q7 = raw_input("What type of information wold be best stored in a text file?: ")
    if q7 == "C" or q7 == "c":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) To write a program with over 1000 lines of code"
    print "B) To create a program that write programs"
    print "C) To create program after program"
    print "D) To create an instance of an object in an object-oriented programming (OOP) language."
    q8 = raw_input("What does instantiate mean?: ")
    if q8 == "D" or q8 == "d":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) It allows you to send the same message to objects of different classes related by inheritance and achieve different and appropriate results"
    print "B) It lets you combine two programs"
    print "C) It creates polygons"
    print "D) It allows you to repeat a loop an infinite amount of times"
    q9 = raw_input("How can polymorphism help a programmer?: ")
    if q9 == "A" or q9 == "a":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) grid()"
    print "B) create_widgets()"
    print "C) root.title"
    print "D) root.mainloop()"
    q10 = raw_input("What widget method sets a widget's options?: ")
    if q10 == "B" or q10 == "b":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) A compass"
    print "B) A graph"
    print "C) A grid"
    print "D) A virtual loop system"
    q11 = raw_input("What is a graphics coordinate system?: ")
    if q11 == "C" or q11 == "c":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) A file with text about sound"
    print "B) A looping sound"
    print "C) A radio channel"
    print "D) Where a sound is stored"
    q12 = raw_input("What's a sound channel?: ")
    if q12 == "D" or q12 == "d":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q13 = raw_input("Can Python increase programmer productivity?: ")
    if q13 == "a" or q13 == "A":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q14 = raw_input("It's not important to use the right types in your programs.: ")
    if q14 == "b" or q14 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q15 = raw_input("You should plan your programs.: ")
    if q15 == "A" or q15 == "a":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q16 = raw_input("Constants aren't helpful.: ")
    if q16 == "b" or q16 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q17 = raw_input("Dictionary keys must be unique.: ")
    if q17 == "a" or q17 == "A":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q18 = raw_input("You should never use docstrings.: ")
    if q18 == "b" or q18 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q19 = raw_input("You should avoid a catch-all exception handling.: ")
    if q19 == "a" or q19 == "A":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q20 = raw_input("An object should never update its private attributes.: ")
    if q20 == "b" or q20 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q21 = raw_input("You should include only related programming elements in a single module.: ")
    if q21 == "a" or q21 == "A":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q22 = raw_input("You can't test which radio button in a group is selected.: ")
    if q22 == "b" or q22 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q23 = raw_input("You should create a batch file to run your graphics programs.: ")
    if q23 == "a" or q23 == "A":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
    print "A) True"
    print "B) False"
    q24 = raw_input("There is no such thing as a sound channel.: ")
    if q24 == "b" or q24 == "B":
        print "Well done you got it right! +1"
        print " "
    else:
        print " no, you're wrong! +0"
else:
    print "Invalid answer."

您可以按如下方式进行操作:

from random import shuffle
list_of_questions = ['A', 'B', 'C', 'D', 'E', and so on]

shuffle(list_of_questions)

question = list_of_questions.pop()
.pop()
方法从列表中删除最后一个问题并返回它。在这种情况下,它总是随机化的,因为这是shuffle所做的,因此它总是最后一个并不重要

例如:

>>> some_list = [1,2,3,4,5]
>>> shuffle(some_list)
>>> some_list
[4,2,5,1,3]
>>> some_list.pop()
3
>>> some_list
[4,2,5,1]
[注] 我还建议您创建一个包含所有问题的单独文本文件(每行1个问题)。使用python,您可以轻松阅读这些问题,并且在将来的某个日期,您还可以轻松地删除或添加新问题,而无需花费太多精力

例如:

#questions.txt         Remember, your questions file will need to be in the same directory as your python script
What is ..?
Who is ..?
Where is ..?
Why is ...?


#Start of your python code
questions = [line.strip() for line in open('questions.txt'. 'r')]


>>> print questions
['What is ...?', 'Who is ...?', 'Where is ...?', 'Why is ...?']

>>> from random import shuffle
>>> shuffle(questions)
>>> print questions.pop()
Where is ...?
>>> print questions
['What is ...?', 'Who is ...?', 'Why is ...?'] #Note the question that was taken is gone from the list. Thanks to the .pop() method

结合csv模块和一些自定义语法进行尝试

下面是一个示例csv文件:

"What is programming?","*Getting your computer to do stuff","A form of watching television","Building a computer","Assembling a computer with your bare hands"
"What does ASCII stand for?","African Standard Code For Information Interchange","*American Standard Code For Information Interchange","American Subtle Codes For Information Interchange","African Subtle Codes For Inside Interchange"
"What is pseudorandom?","A hidden group of words","A group of random letters","*The generation of random numbers by a definite computational process","The way to write code"
"What kinds of elements can you store with a tuple?","Only strings and loops","Only loops","Only strings","*Any type"
...
请注意,每行的第一项是问题,其余的是答案。“正确”答案由开头的
*
表示。该程序将能够轻松解析该文件,任何人工编辑器都可以添加或编辑问题

这是一个将游戏封装在函数中的程序,使用
csv
模块从文件中读取问题和答案,跟踪变量中的分数,并在文件中正确答案的开头自动解析
*
中哪个答案“正确”:

import csv

def play_trivia(questions_path):
    # start the game
    print 'Trivia game:'
    if raw_input("Would you like to begin? (Y/N): ").lower() != 'y':
        print "Goodby."
        return
    print
    score = 0
    # set choice letters (and order)
    letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    # loop through each row in the file
    for row in csv.reader(open(questions_path, 'r')):
        # print the question
        print row[0]
        correct_choice = 'A' # just in case csv is missing the *
        # loop through answers
        # (Start with element 1, since element 0 was the question.)
        for i, choice in enumerate(row[1:]):
            if choice.startswith("*"):
                correct_choice = letters[i]
                print letters[i] + ") " + choice[1:]
            else:
                print letters[i] + ") " + choice
        # ask for the correct answer
        if raw_input("Enter answer: ").upper() == correct_choice:
            score += 1
            print "Well done you got it right! +1 (Score is now " + str(score) + ")"
        else:
            score -= 1
            print "No, you're wrong! -1 (Score is now " + str(score) + ")"
        # separate questions with a line for readability
        print
    # and now we're done
    print "Final score: " + str(score)
请注意,
字母[i]
表示字母中的第i个字母


这在我的python解释器中运行得很好。

请查看
中的
循环:)我强烈建议不要将问题/答案硬编码到python脚本中。OP需要创建数据结构来存储问题和答案。@Ivan,我建议OP创建一个问题文件(每行1个)这样,它可以很容易地分开,也可以很容易地添加更多的问题,而无需太多麻烦。对不起,我仍然感到困惑,我是否应该将问题列表中的“A”、“B”、“C”等更改为“q1”、“q2”、“q3”,并在节目开始时保持这样?@user3470867,是的,我只是为了快速而键入了ABC,这些应该是你的个人问题。另外,我强烈建议您查看我的
[NOTE]
@user3470867,它通过一个问题文件更新了我的答案。希望这能澄清一点。