随机化显示python

时间:2017-09-02 21:36:26

标签: python file

我有以下文件结构 文件结构

1?,a,b,c,d,1
2?,a,b,c,d,2
3?,a,b,c,d,3
4?,a,b,c,d,4
5?,a,b,c,d,5

我的代码如下:

def myfunction(dr):
  print("===H===")
  print("You have selected rating: ", dr)
  question_count=0
  while question_count<5:
    with open('myfile.txt','r') as f:
        reader=csv.reader(f,delimiter=",")
        answer=False
        while answer==False:

           for row in reader:

            if dr=="d": 

              c_a=int(row[6])

              print(row[0])
              print(row[c_a])
              print(row[2])
              print(row[3])
              print(row[4])


            elif dr =="m":

              correct_answer=int(row[6])

              print(row[0])
              print(row[c_a])
              print(row[2])
              print(row[3])

            elif dr=="e": 
               correct_answer=int(row[6])

               print(row[0])
               print(row[c_a])
               print(row[2])

目前,程序读取文件,将正确的答案插入混音中,但我想要它做的是:

将正确的变量插入混合

在这个文件处理结构中,我需要一些随机化的帮助,以及如何不重复正确的答案。

我确实考虑过将所有内容读入列表,然后生成随机输出,但它看起来非常复杂。有更简单的方法吗?

更新

一个建议是使用不同的文件格式,但我想尽可能避免这种情况,尽管请随意在答案中提出这些建议:

我的另一个想法是创建一个列表:在该列表中搜索重复项,然后从该列表中删除重复项(如果有)。

到目前为止,我有这个,它还没有完成,也没有包括随机化的结果列表:

3 个答案:

答案 0 :(得分:0)

  

我确实考虑过将所有内容读入列表,然后生成随机输出,但它看起来非常复杂

它不是,可以导致更少的可重复代码。您可以使用random.shuffle在列表中随机播放答案。看看下面的代码:

import random

def quiz(dr):
    rating_wrongs_count = {'d': 3, 'm': 2, 'e': 1}
    print("===History===")
    print("You have selected rating: ", dr)
    question_count = 0
    # number of wrong answers to include in choices
    wrongs_count = rating_wrongs_count[dr]
    while question_count < 5:
        with open('myfile.txt', 'r') as f:
            reader = csv.reader(f, delimiter=",")
            answer = False
            while not answer:
                for row in reader:
                    correct_answer_idx = int(row[6])
                    correct_answer = row[correct_answer_idx]
                    # get all answers which are not correct answer
                    wrong_answers = [ans for ans in row[1:-1] if ans != correct_answer]
                    random.shuffle(wrong_answers)
                    # get wrongs_count wrong answers and append correct answer
                    choices = wrong_answers[:wrongs_count] + [correct_answer, ]
                    # shuffle and print that list
                    random.shuffle(choices)
                    print(row[0])
                    print("\n".join(choices))

不要忘记设置answer变量并增加question_count变量。我假设它稍后会在您的代码中完成。

答案 1 :(得分:0)

这可能不是最漂亮的解决方案,但绝对有效:

from random import shuffle

if dr=="d": 
    # Number of answers to display
    nAns = 3
    # Position of the correct answer in row
    npos = 3
    # Correct answer
    correct_answer = row[npos]

    # Shuffle all indices except the one with the correct answer 
    # and append the correct answer        
    ind = [i for i in range(1,5) if i!=npos]
    shuffle(ind)
    new_row = [row[i] for i in ind]
    new_row = new_row[:nAns-1]
    new_row.append(correct_answer)

    # Shuffle the resulting list again
    ind = [i for i in range(0,nAns)]
    shuffle(ind)
    new_row = [new_row[i] for i in ind]

答案 2 :(得分:0)

您想要的方法是get_n_choices()。它使用random.sample从答案列表中选择n-1个唯一项目。

请记住将代码分解为函数,以便于阅读和使用。此外,当您发现自己像if那样编写if dr=='d'块时,每个选项看起来与其他选项几乎相同,这是一个很好的指标,您需要将该代码重构为单一功能。

#!/usr/bin/env python3

from random import shuffle, sample
from collections import namedtuple

# namedtuple's provide a nice way of storing simple data and
# using names to access it.
Difficulty = namedtuple('Difficulty', ('name', 'num_answers'))
# Storing your difficulties in a dictionary allows for
# easy lookup.
Difficulty_Settings = {
    'e': Difficulty(name='easy', num_answers=3),
    'm': Difficulty(name='medium', num_answers=4),
    'd': Difficulty(name='difficult', num_answers=5),
}

# Note: There's no error handling here...
# - what if correct_answer_index isn't an integer?
# - what if that index isn't valid for answers?
# - what if answers isn't a list-like object?
def get_n_choices(n, answers, correct_answer_index):
    choices = [answers[correct_answer_index]]
    # Add n - 1 distinct samples from a new answers list
    # omitting the correct answer.
    choices += sample(answers[0:correct_answer_index]
                      + answers[correct_answer_index + 1:], n - 1)
    shuffle(choices)
    return choices


def handle_row(row, difficulty):
    num_choices = Difficulty_Settings[difficulty].num_answers
    # Use unpacking to avoid using indexes, i.e. no row[1], etc.
    # You can use the row you get from the csv reader here instead
    # of the split.
    question, *answers, correct_answer_index = row.split(',')
    # Now that we have the answers in their own list, fix the
    # correct answer index offset
    correct_answer_index = int(correct_answer_index) - 1
    choices = get_n_choices(num_choices, answers, correct_answer_index)
    # Ask question using choices
    print(question)
    print(choices)


if __name__ == '__main__':
    row = "what color is the sky?,red,purple,blue,yellow,green,3"
    handle_row(row, 'd')