I have a 2-dimensional list of random values. I want to take the parts marked by 1 and 0 and separate them to different 1 dimensional lists. Ones only occur diagonally.
I have a list like this.
[[1 if (i // 3) * 3 <= j < (i // 3) * 3 + 3 else 0 for i in range(9)] for j in range(9)]
[[1, 1, 1, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1, 1]]
The actual matrix can have thousands of rows and columns. The rows and columns of 1 blocks can be 10 or 20 or 30. I want to separate 1 and 0 in this list and make a 1 dimensional list for each of them.
list1 = [1,1,1,....,1,1,1]
list0 = [0,0,0,....,0,0,0]
I managed to write a code like this.
diag = [costest[i][j] for i in range(len(costest)) for j in range(len(costest)) if (i // 3) * 3 <= j < (i // 3) * 3 + 3]
nondiag = [costest[i][j] for i in range(len(costest)) for j in range(len(costest)) if (i // 3) * 3 > j or j >= (i // 3) * 3 + 3]
This works but I suspect there might be a better solution. This looks dirty. I googled with the keywords "python 2 dimensional list diagonal part only" but all they showed was a page like this python 3.x - How to change only the diagonal elements of a 2D list? - Stack Overflow
Do you think there is a better solution?