Reputation:
I'm trying to create a list of dictionaries in an array format. Initially I would like the first row and column to have
{'score' : 0, 'pointer' : 'none'}
in each cell, however my for loops do not seem to be carrying this out.
Here is what I have so far:
mymatrix = [[0 for x in range(len(seq1)+1)]for x in range(len(seq2)+1)]
mymatrix[0][0] = {'score' : 0, 'pointer' : 'none'}
for x in mymatrix[0][:]:
x = {'score' : 0, 'pointer' : 'none'}
for y in mymatrix[:][0]:
y = {'score' : 0, 'pointer' : 'none'}
for row in mymatrix:
print row
Where seq1 and seq2 are strings.
Upvotes: 0
Views: 310
Reputation: 4002
You already wrote two for loops in your list comprehension, you can just reuse them.
(I modified your list comprehension, I used y
and x
instead of 2 x
)
seq1 = 'asdfasdfasdf'
seq2 = 'asdfasdfasdf'
mymatrix = [[0 for y in range(len(seq1)+1)]for x in range(len(seq2)+1)]
# ^^^^^^^^^^^^^^^^^^^^^^^^^^ reuse this
d = {'score' : 0, 'pointer' : 'none'}
for y in range(len(seq1)+1):
mymatrix[0][y] = d.copy()
# The first one is already covered, just leave it off using slice
for x in range(len(seq2)+1)[1:]:
mymatrix[x][0] = d.copy()
for line in mymatrix:
print(line)
Out:
[{'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Upvotes: 1
Reputation: 6935
As far as I can tell, the problem is here:
x = {'score' : 0, 'pointer' : 'none'}
This line of code isn't going to mutate the actual matrix. All you're doing here is reassigning the value of the name x
, which is not inherently bound to the matrix you're trying to change. You need to directly reference the matrix. Try this instead:
for xind, x in enumerate(mymatrix[0][:]):
mymatrix[0][xind] = {'score' : 0, 'pointer' : 'none'}
Upvotes: 0