选择一个随机奇数并将其内容添加到不起作用的列表中的程序

2024-09-30 08:29:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建代码,将选择一个随机数,然后使用该数字将文本文件中特定行的内容放入列表中

我不想一个问题被添加到列表中不止一次,所以我做了另一个列表,将包含所有已选择的数字。所有的问题都在奇数线上,答案在偶数线上,所以生成的数字也必须是偶数

下面的代码是我试图做的,但没有运行

import random

#the empty question list
qlist=[0,0,0,0,0]
#the list that is filled with question numbers that have already been chosen
noschosen=[]
file=open('questiontest.txt')
lines=file.readlines()
i=0
#random question chooser
while i<len(qlist):
    chosen=False
    n=random.randint(1,10)
    for index in range(0,len(noschosen)):
        if n==noschosen[index]:
            chosen=True
    #all questions are on odd lines, so the random number can't be even.
    while n%2==0 or chosen==True:
        n=random.randint(1,10)
    #the number chosen is added to the chosen list
    noschosen.append(n)
    #the program adds the question and its answer to qlist
    qlist[i]=(lines[n],lines[n+1])
    #increment
    i=i+1

print (qlist)

这是下一个文件中的内容:

.
Question1
Answer1
Question2
Answer2
Question3
Answer3
Question4
Answer4
Question5
Answer5
Question6
Answer6
Question7
Answer7
Question8
Answer8
Question9
Answer9
Question10
Answer10

第一行的点是故意的

我希望程序以这种方式随机填充列表:

[('QuestionA', 'AnswerA'), 
 ('QuestionB', 'AnswerB'),
 ('QuestionC', 'AnswerC'),
 ('QuestionD', 'AnswerD'),
 ('QuestionE', 'AnswerE')]

字母A。B.C、 D和E代表从1到10的任何一个数字。例如,如果第一个n原来是5,“问题3”和“答案3”将放在第一位(因为第5行是问题3所在的位置)

问题编号及其相应的答案应分组在一起。我不知道为什么我当前的代码不起作用,有人能看到这个问题吗,或者我如何改进这个代码


Tags: the答案代码内容列表that数字random
2条回答

最重要的是,你的行号可以增加到20,但是你只能从前10个行号中选择。更好的是,甚至不用费心去允许一个偶数:取一个随机数1-10,然后从中得到行号:

q_line = 2*n - 1

问题在lines[q_line],答案在下一行


在你一次攻击20行代码之前,你应该学习一些小技巧,让你的生活更轻松。大多数代码可以被random.sample替换,这个方法可以从列表中简单地返回5个随机项。如果你把你的问题和答案组合成一个成对的列表(元组),那么你可以简单地告诉sample你想从这个列表中抓取五对。见here

你只需要检查你得到的第一个随机数是否已经被选中,然后你在这个随机数上生成随机数

while n%2==0 or chosen==True:
    n=random.randint(1,10)

但千万不要检查是否已经选择了新号码

您还可以使用if n in noschosen或make chosen = n in noschosen检查是否选择了数字,并避免for循环

相关问题 更多 >

    热门问题