使用另一个列表索引随机化列表

时间:2017-06-28 23:20:33

标签: python

我正在进行一项测验。我在徘徊是否有人可以帮我解决我一直接受的错误。这是我的代码:

num1 = num = 0
import random

questions = ["What is RAM?","what is ROM","What is a bundle of wires 
carrying data from one component to another?","What does the control unit 
do?"]

ans = [["Random access memory","real access memory","read access 
memory","readable access memory","A"],["Readable object memory","Random 
object memory","Read only memory","Read object memory","C"],
["Bus","Hardware","System software","Embedded systems","A"],["You type on 
it","It sends out control signals to other components","It calculates 
arithmetic problems","Regulates time and speed of computer functions","D"]]

for index in range(0, len(questions)):
    val = [0, 1, 2, 3]
    index = random.choice(val)
    print(questions[index])
    print("\nA:",ans[index][0],"\nB:",ans[index][1],"\nC:",ans[index]
      [2],"\nD:",ans[index][3],"")     
    pa = input("What is your answer?")
    if pa == ans[index][4]:
        num1, num = num1 + 1, num + 1
        print("Correct!\nYou have got",num1,"out of",num,"correct so far\n")
        questions.remove(questions[index])
        ans.remove(ans[index])
        val.remove(index)
    else:
        num = num + 1
        print("incorrect!\nThe correct answer was",ans[index][4],"Your 
         correct questions are Your incorrect questions are")

我试图让它以随机的顺序询问问题,而不是继续向他们提出其他问题答案的问题。有谁知道怎么做? 非常感谢帮助。

2 个答案:

答案 0 :(得分:1)

使用random.shuffle作为索引:

>>> sequence = list(range(len(questions)))
>>> random.shuffle(sequence)
>>> sequence
[2, 0, 3, 1, ....]

然后用

选择问题
for index in sequence:
    question = questions[index]

答案 1 :(得分:0)

我建议将问题和答案合并到一个列表中;一个元组列表。

questions = [('What is RAM?', 'random access memory'), ('What is ROM?', 'read-only memory')]

然后选择一个问题,运行

question = random.choice(questions)

放在一起,它看起来非常接近原始剧本:

import random

questions = [('What is RAM?', 'random access memory'), ('What is ROM?', 'read-only memory')]

while questions:
    question = random.choice(questions)

    print(question[0])
    user_response = input('Reponse> ')
    if user_response == question[1]:
        print('Correct!')
        questions.remove(question)
    else:
        print('Wrong!')

demo