Reputation: 77
So i have
matrix = [['B Borg', '3', '3', '1.0'], ['F Perry', '7', '8', '0.875'], ['R Nadal', '3', '5', '0.6']]
I want to make it look like this:
[['1','B Borg', '3', '3', '1.0'], ['2','F Perry', '7', '8', '0.875'], ['3','R Nadal', '3', '5', '0.6']]
I've tried
matrix.insert([0][0],"1")
matrix.insert([1][0],"2")
matrix.insert([2][0],"3")
But the end result is:
matrix = ["1",",2","3"['B Borg', '3', '3', '1.0'], ['F Perry', '7', '8', '0.875'], ['R Nadal', '3', '5', '0.6']]
My guess is that i messed up the indexing in the insert part, but i just cannot figure out what i did wrong.
Upvotes: 2
Views: 84
Reputation: 304167
If you loop over the matrix, the items will be the things you need to insert into
>>> matrix = [['B Borg', '3', '3', '1.0'], ['F Perry', '7', '8', '0.875'], ['R Nadal', '3', '5', '0.6']]
>>> for i, item in enumerate(matrix, 1):
... item.insert(0, str(i))
...
>>> matrix
[['1', 'B Borg', '3', '3', '1.0'], ['2', 'F Perry', '7', '8', '0.875'], ['3', 'R Nadal', '3', '5', '0.6']]
Upvotes: 0
Reputation: 113955
>>> matrix = [[str(i)]+subl for i,subl in enumerate(matrix, 1)]
>>> matrix
[['1', 'B Borg', '3', '3', '1.0'], ['2', 'F Perry', '7', '8', '0.875'], ['3', 'R Nadal', '3', '5', '0.6']]
Or, use the consume itertools recipe:
>>> matrix = [['B Borg', '3', '3', '1.0'], ['F Perry', '7', '8', '0.875'], ['R Nadal', '3', '5', '0.6']]
>>> collections.deque((subl.insert(0, str(i)) for i,subl in enumerate(matrix, 1)), maxlen=0)
deque([], maxlen=0)
>>> matrix
[['1', 'B Borg', '3', '3', '1.0'], ['2', 'F Perry', '7', '8', '0.875'], ['3', 'R Nadal', '3', '5', '0.6']]
Upvotes: 0
Reputation: 1287
Try this:
matrix2 = [[str(i+1)] + x for i,x in enumerate(matrix)]
Upvotes: 0
Reputation: 365717
The problem is that [0][0]
is the first element in the list [0]
—that is, 0
. So, matrix.insert([0][0], "1")
is the same as matrix.insert(0, "1")
. In other words, it inserts a new row at the top of the matrix, with only a single value, "1"
.
What you want is matrix[0].insert(0, "1")
. Since matrix[0]
is the first row in the matrix, this inserts a new column at the left end of the first row.
Upvotes: 5