How to reverse column order in a matrix with Python?

How to reverse column order in a matrix with Python?

To reverse the column order in a matrix (2D list) using Python, you can use list comprehension. Here's how you can do it:

Using a 2D List

Given a matrix:

matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] 

You can reverse its column order like this:

reversed_matrix = [row[::-1] for row in matrix] 

This will produce:

[ [3, 2, 1], [6, 5, 4], [9, 8, 7] ] 

Using NumPy

If you're working with matrices or large datasets, it's often more efficient to use NumPy, a powerful library for numerical operations in Python. Here's how you can reverse the column order using NumPy:

import numpy as np # Create a NumPy array matrix = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) # Reverse column order reversed_matrix = matrix[:, ::-1] 

The result will be a NumPy array with reversed columns:

array([[3, 2, 1], [6, 5, 4], [9, 8, 7]]) 

You can choose the method that best fits your requirements, whether you're working with standard Python lists or leveraging the efficiency of NumPy arrays.


More Tags

upgrade ngb-datepicker pem underline uiscrollviewdelegate pdfkit signalr healthkit shared homebrew

More Programming Guides

Other Guides

More Programming Examples