Reputation: 513
I have a list of lists and I want to create multiple smaller lists from specific indexes in this list. If I have this big "matrix" can I create a small list made up of integers collected from this matrix?
Code:
matrix = [
[0, 0, 0, 5, 0, 0, 0, 0, 6],
[8, 0, 0, 0, 4, 7, 5, 0, 3],
[0, 5, 0, 0, 0, 3, 0, 0, 0],
[0, 7, 0, 8, 0, 0, 0, 0, 9],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[9, 0, 0, 0, 0, 4, 0, 2, 0],
[0, 0, 0, 9, 0, 0, 0, 1, 0],
[7, 0, 8, 3, 2, 0, 0, 0, 5],
[3, 0, 0, 0, 0, 8, 0, 0, 0],
]
list1 = ([index 1, row 1], [index 2, row 2])
list2 = ([index 3, row 6], [index 7, row 9])
etc.
How would I do this correctly in Python. Help me fill in what would actually go in the parenthesis.
Thanks!
Upvotes: 1
Views: 5094
Reputation: 2971
if index1 means FIRST index, row1 means FIRST row, then matrix[0][0] = 0 in this case. matrix[1][0] = 8 matrix[1][5] = 7
In all, you can do matrix[row_index][col_index]
So
list1 = [ matrix[0,0], matrix[2][2] ]
Hope this helps.
Upvotes: 4
Reputation: 12108
something like this:
newmatrix = []
for n,i in enumerate(matrix[0]):# assuming the lists are in the same length
templist =[]
for l in matrix:
templist.append(l[n])
print "templist: ",n,"content: ",templist
newmatrix.append(templist)
edit: just realized that I completly misread the question. not relevant answer, sorry. not deleting because maybe this could be relevant for someone else
Upvotes: 0
Reputation: 695
You basically have a list of lists here. You call items in a list by:
listname[index]
SO....
matrix[0]
will give you [0, 0, 0, 5, 0, 0, 0, 0, 6]
matrix[0][0]
will give you 0.... that is, the zero-th element of the zero-th list.
Remember, the "first" element of any list is really the zero-th element. So matrix[1] will give you the "second" thing in your list.
list1 = [matrix[1][1], matrix[2][2]]
list2 = [matrix[6][3], matrix[9][7]]
Also a note to help you ask better questions... the examples you gave call for lists but your examples are items grouped by parentheses which denote tuples. Lists are denoted by square brackets. []
Upvotes: 2
Reputation: 4047
list1 = [matrix[1][1], matrix[2][2]]
list2 = [matrix[6][3], matrix[9][7]]
etc...
Upvotes: 4