Search code examples
pythonnumpysortingfloating-pointnested-lists

How to sort a nested list based on a list of floats


I currently have two lists, which look like:

A = [[1.1,2.0,3.3][3.8,50.9,1.0][25.2,6.2,2.2]]
B = [14.4, 0.1, 7.2]

and I would like to sort A based upon the indices of B, such that the resulting sorted lists would look like:

sorted_A = [[3.8,50.9,1.0][25.2,6.2,2.2][1.1,2.0,3.3]]
sorted_B = [0.1,7.2,14.4]

I have tried sorting these using the zip method, trying:

sorted_A = [a for _, a in sorted(zip(B, A))]

but I run into the following error:

"ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

Any help is appreciated, thanks!


Solution

  • You can use zip twice. Also note the key parameter for sorted:

    from operator import itemgetter
    
    A = [[1.1,2.0,3.3],[3.8,50.9,1.0],[25.2,6.2,2.2]]
    B = [14.4, 0.1, 7.2]
    
    sorted_A, sorted_B = zip(*sorted(zip(A, B), key=itemgetter(1)))
    print(sorted_A) # ([3.8, 50.9, 1.0], [25.2, 6.2, 2.2], [1.1, 2.0, 3.3])
    print(sorted_B) # (0.1, 7.2, 14.4)
    

    You can use key=lambda x: x[1] instead of key=itemgetter(1).