Home > Net >  Convert lists into higher dimension so that elements can be reached by following
Convert lists into higher dimension so that elements can be reached by following

Time:11-02

I have a matrix that I want to convert to 3D so that I can be able to print the element of list[i][j][k]

a = [[[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 2, 3, 4,5], [3, 2, 3, 4, 3, 4], [4, 3, 4, 5, 4, 3], [5, 4, 5, 6, 5, 4]]]

print(a[5][5][0]) # I want to be able to print in 3D`

I get right output if I do a[5][5] but wrong when I add the [0]. Is there anyway of converting my matrix such that this will be solved?

I tried to just wrap the list up with brackets [list], but it did not work. I also did: b = [[i] for i in a]

which gave me [[[0,1,2,3,4,5]],[[1,2,3,4,5,6]],... and it still did not work!

NOTE: I want the i to be the row, j to be the column and k to be 0 or 1, so k = 0 (in which case the value is the row index of the cell is pointing to), or the k = 1 (the value is the column index).

CodePudding user response:

Tried to reproduce your issue. To me, it works if you use the right index. Here, it perfectly works if you do for instance

print(a[0][0][5]) # I want to be able to print in 3D`

CodePudding user response:

for list a = [[[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 2, 3, 4,5], [3, 2, 3, 4, 3, 4], [4, 3, 4, 5, 4, 3], [5, 4, 5, 6, 5, 4]]] you have just a[0][n][n]. You can try a[0][5][5] You have index like below:

a = [
        #0 element i
        [
            #0 element j
            [0, 1, 2, 3, 4, 5], 
            #1 element j
            [1, 2, 3, 4, 5, 6], 
            #2 element j
            [2, 3, 2, 3, 4,5], 
            #3 element j
            [3, 2, 3, 4, 3, 4], 
            #4 element j
            [4, 3, 4, 5, 4, 3], 
            #5 element j
            [5, 4, 5, 6, 5, 4]
        ]
    ]

print(a[0][5][5]) # a[i][j][k]

CodePudding user response:

I think this link could be useful for you https://www.geeksforgeeks.org/python-creating-3d-list/

  • Related