Reputation: 2584
How can I reverse the lists of a matrix in python.
EG I have:
example= [1,2,3],
[4,5,6],
[7,8,9]
I want to reverse each row to get the following:
example_reversed = [3,2,1],
[6,5,4],
[9,8,7]
thanks!
Upvotes: 0
Views: 80
Reputation: 45251
This should do it:
[list(reversed(L)) for L in example]
EDIT: Ugh. Way too slow, apparently.
Upvotes: 0
Reputation: 7517
Your matrix currently seems to be stored in a tuple, isn't it?
Anyway, try something like:
list(list(reversed(i)) for i in example)
But you should consider using Numpy if you need to do many computations with matrices.
Upvotes: 1
Reputation: 16711
Map the reversed
function to each item:
newList = map(list, map(reversed, example))
Upvotes: 0
Reputation: 107287
You can use a list comprehension and reverse indexing :
>>> a=[[1,2,3],[4,5,6],[7,8,9]]
>>> [i[::-1] for i in a]
[[3, 2, 1], [6, 5, 4], [9, 8, 7]]
Upvotes: 4