Reputation: 9
I have a matrix [[1 2 3],[4,5,6],[7,8,9]]
How can I reverse it horizontally so it become [[3 2 1],[6,5,4],[9,8,7]]
Upvotes: 0
Views: 384
Reputation: 896
You can try this out:
l= [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# take each list in the list of lists l and reverse that in-place
for item in l:
item.reverse()
print(l)
output:
[[3, 2, 1], [6, 5, 4], [9, 8, 7]]
This is in-place conversion, so no need to create any temporary variables to store values in the inter-mediate steps.
Upvotes: 0
Reputation: 57115
You can use a list comprehension as follows:
m = [[1,2,3],[4,5,6],[7,8,9]]
print([list(reversed(x)) for x in m])
Output:
[[3, 2, 1], [6, 5, 4], [9, 8, 7]]
Upvotes: 0
Reputation: 500663
If a
is your matrix (represented as in your question), the following will flip it horizontally:
map(list.reverse, a)
This will change it in place. If you'd rather create a new matrix:
b = [row[::-1] for row in a]
If you deal with matrices a lot, I'd recommend that you take a look at NumPy. It has a lot of numerical primitives and is very widely used.
Upvotes: 5