Creating a Matrix in Python without numpy

Creating a Matrix in Python without numpy

You need to keep track of the current index in your loop.

Essentially you want to turn a list like 0,1,2,3,4,….24 (these are the indices of your initial array, alpha) into:

R1C1, R1C2, R1C3, R1C4, R1C5
R2C1, R2C2… etc

I added the logic to do this the way you are currently doing it:

def createMatrix(rowCount, colCount, dataList):
    mat = []
    for i in range(rowCount):
        rowList = []
        for j in range(colCount):
            # you need to increment through dataList here, like this:
            rowList.append(dataList[rowCount * i + j])
        mat.append(rowList)

    return mat

def main():
    alpha = [a,b,c,d,e,f,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]
    mat = createMatrix(5,5,alpha)
    print (mat)

main()

which then prints out:

[[a, b, c, d, e], [f, h, i, j, k], [l, m, n, o, p], [q, r, s, t, u], [v, w, x, y, z]]

The reason you were always receiving a,b,c,d,e is because when you write this:

        rowList.append(dataList[j])

what it is effectively doing is it is iterating 0-4 for every row. So basically:

i = 0
rowList.append(dataList[0])
rowList.append(dataList[1])
rowList.append(dataList[2])
rowList.append(dataList[3])
rowList.append(dataList[4])
i = 1
rowList.append(dataList[0]) # should be 5
rowList.append(dataList[1]) # should be 6
rowList.append(dataList[2]) # should be 7
rowList.append(dataList[3]) # should be 8
rowList.append(dataList[4]) # should be 9

etc.

You can use a list comprehension:

>>> li= [a,b,c,d,e,f,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]
>>> [li[i:i+5] for i in range(0,len(li),5)]
[[a, b, c, d, e], [f, h, i, j, k], [l, m, n, o, p], [q, r, s, t, u], [v, w, x, y, z]]

Or, if you dont mind tuples, use zip:

>>> zip(*[iter(li)]*5)
[(a, b, c, d, e), (f, h, i, j, k), (l, m, n, o, p), (q, r, s, t, u), (v, w, x, y, z)]

Or apply list to the tuples:

>>> map(list, zip(*[iter(li)]*5))
[[a, b, c, d, e], [f, h, i, j, k], [l, m, n, o, p], [q, r, s, t, u], [v, w, x, y, z]]

Creating a Matrix in Python without numpy

Leave a Reply

Your email address will not be published. Required fields are marked *