How would one approach sorting a numpy array using the index of a second array as the key in python

Viewed 32

I am struggling with sorting a list of ndarrays using index of a second binary list. For example, if I have:

List1 = ([ndarray1][ndarray2][ndarray3][ndarray4])
List2 = [1,0,1,1]

I wish to use the index of List2 position of 0 and 1 to sort List1. In this example, the outcome would be:

List3 = ([ndarray1][ndarray3][ndarray4])
List4 = ([ndarray2])

Your help would be appreciated.

2 Answers

I believe you could use enumerate (read more on https://realpython.com/python-enumerate/) and loop through the enumerate values to achieve the desired result. Cheers!

List1 = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
List2 = [1,0,1,1]

List3 = []
List4 = []

for key, decision in enumerate(List2):
    if decision == 1:
        List3.append(List1[key])
    else:
        List4.append(List1[key])
print("List3 = ", List3)
print("List4 = ", List4)

Results would be:

List3 =  [[1, 2, 3], [7, 8, 9], [10, 11, 12]]
List4 =  [[4, 5, 6]]

short lines

lst1 = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
_filter = [1,0,1,1]
list(
  filter(
    None,
    [lst1[i] if val > 0 else None for i,val in zip(range(0,len(_filter)), _filter)]
  )
)
[x[1] for x in list(filter(lambda x: x[0] != 0, zip(_filter, lst1)))]
Related