Skip to content Skip to sidebar Skip to footer

Tuples In Python To 3D Matrix

I have a list of lists in python that contains the score of users in a game with different courses and levels. My tuple (users, courses, levels, scores). I ve got 20 users 4 course

Solution 1:

If you really need the data in that form, you could do something like:

data = [(110, 'Math', 1, 5),
(110, 'Sports', 1,  5),
(110, 'Geography', 1, 10),
(112, 'History', 1,  9),
(112, 'History', 2,  10)] #I'm using Python 3 -- u'' is superfluous

dataDict = {(x,y,z):w for x,y,z,w in data}

users = [110,112] #extend as needed. Also -- easily grabbed by code
subjects = ['Math', 'Sports', 'Geography', 'History'] #etc
levels = [1,2] #etc.

#first create a matrix of the right shape initialized to zeros:

dataMatrix = [[[0 for k in range(len(levels))] for j in range(len(subjects))] for i in range(len(users))]

#then load the nonzeros:

for i,u in enumerate(users):
    for j,s in enumerate(subjects):
        for k,l in enumerate(levels):
            if (u,s,l) in dataDict: dataMatrix[i][j][k] = dataDict[u,s,l]

To view it, do something like:

>>> for layer in dataMatrix: print(layer)

[[5, 0], [5, 0], [10, 0], [0, 0]]
[[0, 0], [0, 0], [0, 0], [9, 10]]

the first layer is the 2-D matrix corresponding to the first user, etc.

Having done all this -- I really don't see any reason anybody would want to use dataMatrix rather than dataDict.


Post a Comment for "Tuples In Python To 3D Matrix"