How to Sort Arrays in a List in Python?

Estimated read time 2 min read

To sort arrays in a list in Python, you can use the sorted() function with a lambda function as the key argument. The lambda function should specify the sorting key for each array.

Here’s an example implementation:

import numpy as np

# Define a list of arrays
my_list = [np.array([4, 2, 8]), np.array([1, 3, 9]), np.array([6, 5, 7])]

# Sort the arrays in the list based on the sum of their values
sorted_list = sorted(my_list, key=lambda x: np.sum(x))

# Print the sorted list
print(sorted_list)

In this example, we define a list my_list of arrays. We use the sorted() function to sort the arrays in the list based on the sum of their values. We use a lambda function lambda x: np.sum(x) as the key argument to specify the sorting key for each array. The lambda function computes the sum of the values in each array, which is used to determine the order in which the arrays are sorted. We then assign the sorted list to the sorted_list variable and print it.

Note that the sorted() function returns a new sorted list, and does not modify the original list. If you want to modify the original list in place, you can use the sort() method of the list instead:

# Sort the arrays in the list in place based on the maximum value
my_list.sort(key=lambda x: np.max(x))

# Print the modified list
print(my_list)

In this example, we use the sort() method of the list to sort the arrays in place based on the maximum value in each array. We use a lambda function lambda x: np.max(x) as the key argument to specify the sorting key for each array. The lambda function computes the maximum value in each array, which is used to determine the order in which the arrays are sorted. We then print the modified list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply