John
John

Reputation: 55

Storing object into 2 dimensional array/list

Scenario: one person takes a quiz with 10 questions - question number, answer A, B ,C or D and whether they got it correct - true false. I wrote this little program to generate 10 results for the ten questions of a quiz:

import random
class Response:
    def __init__(self):
        self._qno=1
        self._response=  chr(random.randrange(65,68))
        x=random.randint(0,1)
        if x==1:
          self._correct=True
        else:
          self._correct=False

classTest=[Response() for x in range(10)]

for n in range(10):
    classTest[n]._qno=n
    print (classTest[n]._qno,classTest[n]._response,classTest[n]._correct)

It does exactly what I want to do. However, if I create a 2d array of results for 20 pupils taking a quiz the I cannot get any sort of output like the one above:

Here is the code - any ideas? I have tried using the attributes and you will see here the methods. I have tried things like classtest[2][3]._distract to no avail.

import numpy
import random

class Response:
    def __init__(self):
        self._qno=1
        self._distract= chr(random.randrange(65,68))
        x=random.randint(0,1)
        if x==1:
          self._correct=True
        else:
          self._correct=False

    def getqno(self):
        return self._qno

    def getDistract(self):
        return self._distract

row,column=(20,10)
classTest=[Response() for x in range(column) for y in range(row)]

for list in classTest:
    for item in list:
        print(item.getDistract())

Upvotes: 0

Views: 72

Answers (1)

shortorian
shortorian

Reputation: 1182

I think you have an error in your classTest list comprehension. If you want 20 lists of 10 responses, do

classTest=[[Response() for x in range(column)] for y in range(row)]

Upvotes: 1

Related Questions