0

I'm trying to sort a list of tuples by the first value in ascending or descending order based on the order variable in the input being 'ascending' or 'descending'. i tried something like this code below but didn't work. can you please help me correct this ?

sample input: [(2.0, array([1., 0., 0.])), (1.0, array([0., 1., 0.])), (3.0, array([0., 0., 1.]))]

[code]

def sort_eigen_pairs(Ep, order = 'ascending'):

    if(order=='descending'):
        Ep = Ep.sort(reverse=True)

    else:
        Ep=Ep.sort()

    return Ep
VishwaV
  • 167
  • 12

1 Answers1

0

Your input Ep is a list of tuples. Lists are mutable which means they change themselves when you apply a function and have no return value. The sort function will automatically look at only the first element of the tuple. The solution is to remove the Ep = but note that this will only work if you input Ep is always a list of tuples.

def sort_eigen_pairs(Ep, order = 'ascending'):

    if(order=='descending'):
        Ep.sort(reverse=True)

    else:
        Ep.sort()

    return Ep
wgb22
  • 247
  • 1
  • 13
  • Hi @VishwaV! Glad to hear this worked. Can you consider accepting this answer? By signalling the question as resolved, it will help others with a similar issue find this solution more quickly. Thanks! – wgb22 Oct 07 '19 at 01:20