Creating a matrix in Python without numpy

I am trying to create and initialize a matrix. Where I have a problem, each row of my matrix that I create is the same, and not moving around a dataset. I tried to fix this by checking if the value was already in the matrix and that did not solve my problem.

def createMatrix(rowCount, colCount, dataList):   
mat = []
for i in range (rowCount):
    rowList = []
    for j in range (colCount):
        if dataList[j] not in mat:
            rowList.append(dataList[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)

The result should be as follows: ['a', 'b', 'c', 'd', 'e'], ['f', 'h', 'i', 'j', 'k'], [ 'l', 'm', 'n', 'o', 'p'], ['q', 'r', 's',' t ',' u '], [' v ',' w ',' x ',' y ',' g ']

My problem is that I just get the first list a, b, c, d, e for all 5 lists returned

+4
2

.

, , , 0,1,2,3,4,.... 24 ( , alpha) :

R1C1, R1C2, R1C3, R1C4, R1C5 R2C1, R2C2... ..

, , :

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()

:

[['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']]

, a,b,c,d,e, , :

        rowList.append(dataList[j])

, , 0-4 . , :

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

...

+3

:

>>> 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']]

, , 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')]

list :

>>> 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']]
+1

Source: https://habr.com/ru/post/1658147/


All Articles